1.使用了额外的数组。空间复杂度O(N),时间复杂度O(N)
class Solution {
public int findDuplicate(int[] nums) {
if (nums == null||nums.length == 0) {
return 0;
}
int[] copy = new int [nums.length+1];
for(int j = 0; j<copy.length; j++){
copy[j] = -1;
}
for(int i = 0;i < nums.length;i++){
if(copy[nums[i]]==-1){
copy[nums[i]] = nums[i];
}else{
return nums[i];
}
}
return 0;
}
}
2.快慢指针
class Solution {
public int findDuplicate(int[] nums) {
int slow = nums[0];
int fast = nums[nums[0]];
//寻找相遇点
while (slow != fast) {
slow = nums[slow];
fast = nums[nums[fast]];
}
//slow 从起点出发, fast 从相遇点出发, 一次走一步
slow = 0;
while (slow != fast) {
slow = nums[slow];
fast = nums[fast];
}
return slow;
}
}