1.置换法n,1-最优
class Solution {
public int findRepeatNumber(int[] nums) {
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;
}
}
2.先排序nlogn,logn
3.hash法n,n
class Solution {
public int findRepeatNumber(int[] nums) {
HashSet<Integer> set = new HashSet<>();
for(Integer i:nums){
if(set.contains(i)){
return i;
}
set.add(i);
}
return -1;
}
}