LeetCode 287 find the duplicate number
we have an array with length of n+1, and it contains from 1 to n. and that means we can only one duplicate number. return this duplicate number.
remember: we are not saying that all the numbers are in an order, actually they are not.
and we also need to know that this duplicate number can be appears for more than 2 times.
idea:
of course we can sort the array and iterate them to check each adjacent pair is duplicate or not.
class Solution {
public int findDuplicate(int[] nums) {
if (nums == null || nums.length <= 1) {
return 0;
}
Arrays.sort(nums);
for (int i = 0; i < nums.length - 1; i++) {
if (nums[i] == nums[i+1]) {
return nums[i];
}
}
return -1;
}
}
but that’s not what this problem meant for, we actually want to solve this problem in time complexity of less than O(n^2) and in the meantime we don’t need to modify the input array.
so we use drawer principle, and we use binary search.
class Solution {
//解法1是抽屉原理
public int findDuplicate(int[] nums) {
int min = 0;
int max = nums.length - 1;
while(min <= max){
int mid = (max - min) / 2 + min;
int count = 0;
for(int i = 0; i<nums.length; i++){
if(nums[i] <= mid){
count++;
}
}
if(count > mid){ //如果小雨等于mid的数量>mid值,那就说明前半段里面肯定存在重复的
max = mid - 1;//因此缩小范围 降低下界
} else{
min = mid + 1;
}
}
return max + 1; //replace this with min is fine too
}
}
//为什么说 /如果小雨等于mid的数量>mid值,那就说明前半段里面肯定存在重复的 ?
//想象一下一个极端情况:【1,2,3,4,4, 4】
//min = 0 max = 5 mid = 2
//so count will be 2, and count <= mid, so the duplicate must exists in the right part

浙公网安备 33010602011771号