题目:
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.
分析:因为重复数字必在1-n之间,我们利用二分查找方法,初始化left = 1, right = n, 不防假设重复数字为mid = (left + right)/2.然后遍历数组,计算小于等于mid的元素个数num,若num > mid,则只需在left和mid-1之间查找重复的数,否则在mid+1和right之间查找重复的数。当不满足循环条件left <= right时,整数left即为要查找的重复的数。
Java代码如下:
public int findDuplicate(int[] nums) { int left = 1; int right = nums.length - 1; while (left <= right) { int mid = (left + right)/2; int num = countNum(nums, mid); if (num > mid) { right = mid - 1; } else { left = mid + 1; } } return left; } public int countNum(int[] nums, int target) { int sum =0; for (int i = 0; i < nums.length; i++) { if (nums[i] <= target) { sum++; } } return sum; }