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. Example 1: Input: [1,3,4,2,2] Output: 2 Example 2: Input: [3,1,3,4,2] Output: 3 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. Solution 1 2 3 https://leetcode.com/problems/find-the-duplicate-number/solution/ Binary search : Nice solution. A quick explanation for these don't understand the idea behind the scenes. The binary search is utilizing the fact that the duplicate number could only occur in the "denser" half of the array (This is only true, we have no missing numbers from 1 to n). So we should set low or high to move towards the denser half. Eventually when low exceeds high we will get the duplicated number. Input: [1,3,4,2,2] Output: 2
class Solution { public int findDuplicate(int[] nums) { int left = 0; // 0, 0, 1, 2 int right = nums.length - 1; // 4 , 1 , 1, 1 while(left <= right){ int mid = left + (right - left) / 2; // 2, 0, 1 int count = 0; for(int a : nums){ if(a <= mid) count++; // count = 3, 0 ,1 } if(count <= mid) left = mid + 1; // 1 , 2 else right = mid - 1; // right = mid - 1 = 2 - 1 = 1 } return left;// 2 } } Input: [1,3,4,2,2] Output: 2
這個解法用 count 來 數 數組中一共有多少位在mid value 以前, 這樣就不用 sort 這個array 了數組
若是原本有兩個在前面, 可是 數出來三個, 就說明 多餘的那個 就在前面, otherwise, 在後面less
This solution is based on binary search.ide
At first the search space is numbers between 1 to n. Each time I select a number mid
(which is the one in the middle) and count all the numbers equal to or less than mid
. Then if the count
is more than mid
, the search space will be [1 mid]
otherwise [mid+1 n]
. I do this until search space is only one number.ui
Let's say n=10
and I select mid=5
. Then I count all the numbers in the array which are less than equal mid
. If the there are more than 5
numbers that are less than 5
, then by Pigeonhole Principle (https://en.wikipedia.org/wiki/Pigeonhole_principle) one of them has occurred more than once. So I shrink the search space from [1 10]
to [1 5]
. Otherwise the duplicate number is in the second half so for the next step the search space would be [6 10]
.this