題目描述
找出數(shù)組中重復的數(shù)字。
在一個長度為 n 的數(shù)組 nums 里的所有數(shù)字都在 0~n-1 的范圍內(nèi)。數(shù)組中某些數(shù)字是重復的,但不知道有幾個數(shù)字重復了,也不知道每個數(shù)字重復了幾次。請找出數(shù)組中任意一個重復的數(shù)字。
示例 1:
輸入:
[2, 3, 1, 0, 2, 5, 3]
輸出:2 或 3
方法一
class Solution {
public int findRepeatNumber(int[] nums) {
Set<Integer> set = new HashSet<Integer>();
int repeat = -1;
for (int num : nums) {
if (!set.add(num)) {
repeat = num;
break;
}
}
return repeat;
}
}
方法二
class Solution {
public int findRepeatNumber(int[] nums) {
if(nums.length <=0){
return -1;
}
int x;
for(int i=0; i<nums.length; i++){
while(nums[i]!=i){
if(nums[i]==nums[nums[i]]){
return nums[i];
}
int temp=nums[i];
nums[i]=nums[temp];
nums[temp]=temp;
}
}
return -1;
}
}
備注:兩種方法
1.用集合,建立一個空的集合,遍歷nums,放進去的之后就不能放了,就是重復的
2.原地置換,如上圖所示