Given an array nums containing n + 1 integers where each integer is between 1 andn (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题目链接:https://leetcode.com/problems/find-the-duplicate-number/
题目大意:一个数组包含n+1个在1-n中的数字,找出重复出现的数,重复的数可能不止重复一次,要求空间O(1),时间小于O(n^2),数组只读。
题目分析:二分答案,如果数组中小于二分值的个数大于等于二分值本身,说明重复的数字肯定是小于二分值的
public class Solution { public int findDuplicate(int[] nums) { int len = nums.length; int left = 1, right = len - 1, mid = 0, count = 0; while(left <= right) { mid = (left + right) >> 1; count = 0; for(int i = 0; i < len; i++) { if(nums[i] < mid) { count ++; } } if(count >= mid) { right = mid - 1; } else { left = mid + 1; } } return right; } }