1、找出数组中的重复数字
找出数组中重复的数字
在一个长度为 n 的数组 nums 里的所有数字都在 0~n-1 的范围内。数组中某些数字是重复的,但不知道有几个数字重复了,也不知道每个数字重复了几次。请找出数组中任意一个重复的数字。
题目链接:https://leetcode-cn.com/problems/shu-zu-zhong-zhong-fu-de-shu-zi-lcof/
示例 1:
输入:
[2, 3, 1, 0, 2, 5, 3]
输出:2 或 3
解法:
-
直接使用set集合来做,往集合中添加元素,遇到重复值即返回false。return值即可。
class Solution {
public int findRepeatNumber(int[] nums) {
int[] arr = new int[nums.length];
for(int i = 0; i < nums.length; i++){
arr[nums[i]]++;
if(arr[nums[i]] > 1)
return nums[i];
}
return -1;
}
}
2. 因为数字是在1~n-1的,所以new一个长度为n的数组,每次给数组中数字对应的下标位置加一,当new出的数组中的值有大于1的时候返回。
class Solution {
public int findRepeatNumber(int[] nums) {
HashSet<Integer> set = new HashSet<>();
for (int num : nums) {
if (!set.add(num))
return num;
}
return -1;
}
}
3. 但是前二种方法用时都比较高,因此考虑有没有其他的解法。
-
既然是 nums 里的所有数字都在 0~n-1 的范围内。那么我们可以发现,如果没有重复的数字的话,正常排序后,数字i应该是在下标为i的位置,因此可以考虑从头扫描数组,如果数组中下标为i的位置不是数字i(如果是x)的话,那么就与下标为x的数字交换,交换过程中如果遇到重复的数字就返回。
class Solution {
public int findRepeatNumber(int[] nums){
int temp;
for(int i=0;i<nums.length;i++){
while (nums[i]!=i){
if(nums[i]==nums[nums[i]]){
return nums[i];
}
temp=nums[i];
nums[i]=nums[temp];
nums[temp]=temp;
}
}
return -1;
}
}