题目

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:

  1. Input: [1,3,4,2,2]
  2. Output: 2

Example 2:

  1. Input: [3,1,3,4,2]
  2. Output: 3

Note:

  1. You must not modify the array (assume the array is read only).
  2. You must use only constant, O(1) extra space.
  3. Your runtime complexity should be less than O($n^2$).
  4. There is only one duplicate number in the array, but it could be repeated more than once.

题意

思路

链表循环查找:参考 官方解答

二分查找:参考 [LeetCode] 287. Find the Duplicate Number 寻找重复数


代码实现

Java

链表循环

  1. class Solution {
  2. public int findDuplicate(int[] nums) {
  3. int slow = nums[0], fast = nums[0];
  4. do {
  5. slow = nums[slow];
  6. fast = nums[nums[fast]];
  7. } while (slow != fast);
  8. fast = nums[0];
  9. while (fast != slow) {
  10. slow = nums[slow];
  11. fast = nums[fast];
  12. }
  13. return slow;
  14. }
  15. }

二分查找

  1. class Solution {
  2. public int findDuplicate(int[] nums) {
  3. int left = 1, right = nums.length - 1;
  4. while (left < right) {
  5. int mid = (right - left) / 2 + left;
  6. int count = 0;
  7. for (int num : nums) {
  8. if (num <= mid) {
  9. count++;
  10. }
  11. }
  12. if (count <= mid) {
  13. left = mid + 1;
  14. } else {
  15. right = mid;
  16. }
  17. }
  18. return left;
  19. }
  20. }