Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate number must exist. Assume that there is only one duplicate number, find the duplicate one.
Note:
- You must not modify the array (assume the array is read only).
- You must use only constant, O(1) extra space.
- Your runtime complexity should be less than
O(n2). - There is only one duplicate number in the array, but it could be repeated more than once.
binary search, O(nlgn), get middle value, count number of value less than middle, if true search upper part, false to search lower part.
public class Solution {
public int findDuplicate(int[] nums) {
int len = nums.length;
int low = 1, high = len -1;
int mid = 0;
while(low<high) {
mid = low + (high-low)/2;
int c = count(nums, mid);
if(c > mid) {
high = mid;
}else{
low = mid+1;
}
}
return low;
}
public int count(int[] nums, int mid) {
int res = 0;
for(int i=0;i<nums.length;i++){
if(nums[i]<=mid) res++;
}
return res;
}
}

本文介绍了一种使用二分查找算法在只读数组中找到重复数字的方法。该算法的时间复杂度为O(n log n),且仅使用常数级额外空间。文章详细解释了如何通过不断调整中间值来缩小搜索范围,直至找到重复的数字。
544

被折叠的 条评论
为什么被折叠?



