当前位置:网站首页>剑指 Offer | 03. 数组中重复的数字
剑指 Offer | 03. 数组中重复的数字
2022-08-04 22:04:00 【孤天野鹤】
剑指 Offer 03. 数组中重复的数字 - 力扣(LeetCode)
https://leetcode.cn/problems/shu-zu-zhong-zhong-fu-de-shu-zi-lcof/今天开个坑,刷一波剑指offer(虽然零散刷过一点。。。
法一:利用HashSet可以快速查找的特点,将元素放入HashSet中并比较。
class Solution {
public int findRepeatNumber(int[] nums) {
HashSet<Integer> integers = new HashSet<>();
for (int i = 0; i < nums.length; i++) {
if (integers.contains(nums[i])) {
return nums[i];
}
integers.add(nums[i]);
}
return -1;
}
}法二:下标法, 不断交换元素,使元素与其对应下标 相同,直至发生冲突。
class Solution {
public int findRepeatNumber(int[] nums) {
// 遍历数组
for(int i = 0; i < nums.length; i++) {
// 之所以用while,是因为交换之后,该位置的元素任然没有在正确的位置
while(i != nums[i]){
if(nums[i] == nums[nums[i]]){
return nums[i];
}
// nums[i] 正确的位置在 nums[nums[i]]
int k = nums[nums[i]];
nums[nums[i]] = nums[i];
nums[i] = k;
}
}
return -1;
}
}边栏推荐
- Cocoa Application-test
- 打卡第 2 天: urllib简记
- 软件测试外包公司怎么样?有什么好处和坏处?为什么没人去?
- numpy关于两个array叠加操作
- Rocketchip RISC-V Debug调试硬件相关(四)hartIsInReset
- Hardware factors such as CPU, memory, and graphics card also affect the performance of your deep learning model
- ctfshow终极考核web654
- EasyGBS接入最新版海康摄像头后无法传递告警信息该如何解决?
- Oracle增加表空间解决ORACLE ORA-01653: unable to extend table报错
- Qt面试题整理
猜你喜欢

Open source summer | Cloud server ECS installs Mysql, JDK, RocketMQ

炽热如初 向新而生|ISC2022 HackingClub白帽峰会圆满举办!

基于 Milvus 和 ResNet50 的图像搜索(部署及应用)

Arduino 电机测速

强网杯2022——WEB

七夕,当爱神丘比特遇上牛郎和织女
![[Linear Algebra 03] Elimination method display and 4 solutions of AX=b](/img/29/fd79222e5bec26851974abd86a2013.png)
[Linear Algebra 03] Elimination method display and 4 solutions of AX=b
![Rt-thread [二] 系统初始化流程](/img/46/6e2942e4c18c0220378050205e6528.png)
Rt-thread [二] 系统初始化流程

ES6高级-async的用法

Cocoa Application-test
随机推荐
Altium Designer 19.1.18 - Protecting Locked Objects
Driving point cloud format changes bring efficiency improvement
七夕特制:《牛郎会织女》
【QT】回调函数的实现
MySQL查询为啥慢了?
VSCode—常用快捷键(持续记录
Numpy on the superposition of two arrays
MQTT[一]基础知识介绍
如何一键重装win7系统?重装win7系统详细教程
Lecture 2 Software Life Cycle
Webmine Webpage Mining Trojan Analysis and Disposal
Is the International Project Manager PMP certificate worth taking?
Ramnit感染型病毒分析与处置
热力学相关的两个定律
OC-类簇
论文解读(PPNP)《Predict then Propagate: Graph Neural Networks meet Personalized PageRank》
【C - 基本概念】
In action: 10 ways to implement delayed tasks, with code!
三个多月、40余场面试浓缩为6000字
Qt面试题整理