题目:
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.Binary Tree
public int findDuplicate(int[] nums) {
int start = 1, end = nums.length - 1;
while (start + 1 < end) {
int mid = start + (end - start) / 2;
int left = 0, right = 0;
for (int a : nums) {
if (a <= mid) left++;
}
if (left <= mid) start = mid;
else end = mid;
}
int countStart = 0, countEnd = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] == start) countStart++;
if (nums[i] == end) countEnd++;
}
return countStart > countEnd ? start : end;
}
2.LinkedList Find the starting point of circle
public int findDuplicate(int[] nums) {
int n = nums.length;
int slow = nums[0];
int fast = nums[nums[0]];
while (slow != fast) {
slow = nums[slow];
fast = nums[nums[fast]];
}
fast = 0;
while (slow != fast) {
slow = nums[slow];
fast = nums[fast];
}
return slow;
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。