当前位置:网站首页>剑指 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;
}
}边栏推荐
- Webmine Webpage Mining Trojan Analysis and Disposal
- com.jacob.com.ComFailException: Invoke of: ActiveDocument
- 软件测试外包公司怎么样?有什么好处和坏处?为什么没人去?
- The use and principle of CountDownLatch
- 【社媒营销】WhatsApp Business API:您需要知道的一切
- Oracle增加表空间解决ORACLE ORA-01653: unable to extend table报错
- 驱动点云格式修改带来的效率提升
- y87.第五章 分布式链路追踪系统 -- 分布式链路追踪系统起源(一)
- EasyGBS接入最新版海康摄像头后无法传递告警信息该如何解决?
- [larave]关于laravel使用form submit()不能获取值问题
猜你喜欢
随机推荐
【线性代数02】AX=b的2种解释和矩阵乘法的5种视角
Analysis and treatment of Ramnit infectious virus
Ramnit感染型病毒分析与处置
今天是七夕,来看看程序员的土味情话。
备战9月,美团50道软件测试经典面试题及答案汇总
LocalDateTime的详细使用方法
MQTT[一]基础知识介绍
# #ifndef/#define/#endif使用详解
热力学相关的两个定律
立方度量(Cubic Metric)
ES6高级-Promise的用法
Numpy on the superposition of two arrays
Unknown point cloud structure file conversion requirements
打卡第 1 天:正则表达式学习总结
How to right use of WebSocket in project
y87.第五章 分布式链路追踪系统 -- 分布式链路追踪系统起源(一)
Altium Designer 19.1.18 - draw polygons copper hollow out, for the cursor just capture solutions
Altium Designer 19.1.18 - Protecting Locked Objects
双非读者,一举拿下阿里、字节、美团、京东、虾皮offer
力扣19-删除链表的倒数第 N 个结点——链表








