Find the Duplicate Number
ID: 633; medium; 寻找重复的数
Last updated
ID: 633; medium; 寻找重复的数
Last updated
The array is not sorted
Time complexity should be less than
Space complexity should be
We know that the range of the numbers is initially [1, n]
. We take the middle element inside the range mid
. If count ≤ mid
, where count
is the number of elements that are less than or equal to mid
, then we are certain that the duplicated number is not inside the range [left, mid]
. The reason is the following:
Original array: [3, 1, 4, 6, 5, 8, 8, 9]
Range: [1, 9]
left
right
mid
count
Result
1
9
5
4 bc the smaller number are 3, 1, 4, 5
count ≤ mid
New range is [5, 9]
and 8 is inside that range.✅
Maybe think about [3, 8, 8, 4, 6, 1, 5, 9]
. Length - 1?
Time complexity for this solution is
Space complexity should be
Time complexity: O(nlogn)
Space complexity: O(logn) or O(n), does not meet the requirement for this problem but indeed a solution
Use a set to find the duplicated number
If the set already contains a number when adding it, it is the duplicated one.
A similar idea as used in Linked Cycle II.