LeetCode刷题实战287:寻找重复数
Given an array of integers nums containing n + 1 integers where each integer is in the range [1, n] inclusive.
There is only one repeated number in nums, return this repeated number.
You must solve the problem without modifying the array nums and uses only constant extra space.
示例
输入:nums = [1,3,4,2,2]
输出:2
示例 2:
输入:nums = [3,1,3,4,2]
输出:3
示例 3:
输入:nums = [1,1]
输出:1
示例 4:
输入:nums = [1,1,2]
输出:1
解题
public int findDuplicate(int[] nums) {
int low = 1,high = nums.length,mid = 0;
while(low < high) {
mid = low + (high-low)/2;
//System.out.println(low+" "+high+" "+mid);
int count = 0;
for(int num:nums) {
if(num <= mid) {
count++;
}
}
if(count > mid) { //如果严格大于的话,说明在(0,mid)这个范围内肯定有重复的元素
high = mid;
}else {
low = mid+1;
}
}
return low;
}
}
public int findDuplicate(int[] nums) {
int fast = 0,slow = 0;
do {
//因为数组元素范围都在1~n,所以不会越界
slow = nums[slow];
fast = nums[fast];
fast = nums[fast];
}while(fast != slow);
//fast和slow相交的地方并不是环形入口
slow = 0;
//A = C找环形入口
while(slow != fast) {
slow = nums[slow];
fast = nums[fast];
}
return slow;
}
}
赞 (0)