找出数组中重复的数字。
在一个长度为 n 的数组 nums 里的所有数字都在 0~n-1 的范围内。数组中某些数字是重复的,但不知道有几个数字重复了,也不知道每个数字重复了几次。请找出数组中任意一个重复的数字。
示例 1:
输入:
[2, 3, 1, 0, 2, 5, 3]
输出:2 或 3
来源:力扣(LeetCode)
最容易想到的:
class Solution {
public int findRepeatNumber(int[] nums) {
HashMap<Integer,Integer>hm=new HashMap<Integer,Integer>();
for(int i=0;i<nums.length;i++){
if(hm.containsKey(nums[i]))
return nums[i];
else
hm.put(nums[i],1);
}
return -1;
}
另外,注意到数字都在0~n-1 的范围内,可以把原数组原地当作哈希表来存储。同leetcode第41题思路
class Solution {
public int findRepeatNumber(int[] nums) {
for(int i=0;i<nums.length;i++){
int a=Math.abs(nums[i]);
if(nums[a]<0)
return a;
else
nums[a] *=-1;
}
return 0;
}
}
本文介绍了一种寻找数组中重复数字的方法,特别适用于数组元素范围在0到n-1的情况。提供了两种解决方案,一种使用HashMap实现,另一种利用数组原地作为哈希表的方法。
336

被折叠的 条评论
为什么被折叠?



