在一个长度为 n 的数组 nums 里的所有数字都在 0~n-1 的范围内。数组中某些数字是重复的,但不知道有几个数字重复了,也不知道每个数字重复了几次。请找出数组中任意一个重复的数字。
示例 1:
输入:
[2, 3, 1, 0, 2, 5, 3]
输出:2 或 3
限制:
2 <= n <= 100000
class Solution {
public int findRepeatNumber(int[] nums) {
if(nums == null || nums.length == 0){
return -1;
}
for(int i = 0 ; i < nums.length ; i++){
if(nums[i] < 0 || nums[i] > nums.length - 1 ){
return -1;
}
if(nums[i] != i){
if (nums[i] == nums[nums[i]]){
return nums[i];
} else {
int temp = nums[nums[i]];
nums[nums[i]] = nums[i];
nums[i] = temp;
i--;
}
}
}
return -1;
}
}
方案1:数组先排序,从头到尾扫描排序后的数组。
方案2:创建一个hash表,hash表当前是否包含该数字,如果有数字则就找到一个重复数字。
方案3:从头到尾扫描数字,当扫描数字下标为i时,比较这个数字是否等于i。
如果等于:则向下走。
如果不等于:则比较、交换。
网友评论