[LeetCode] 287. Find the Duplicate Number 寻找重复数

Posted 轻风舞动

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode] 287. Find the Duplicate Number 寻找重复数相关的知识,希望对你有一定的参考价值。

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:

  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(n2).
  4. There is only one duplicate number in the array, but it could be repeated more than once.

寻找一个数组里的重复数,由于只能O(1)的空间复杂度,所以哈希表之类的就不能用了。

解法1: 双指针,寻找环。类似于 142. Linked List Cycle II

Treat each (key, value) pair of the array as the (pointer, next) node of the linked list, thus the duplicated number will be the begin of the cycle in the linked list. Besides, there is always a cycle in the linked list which starts from the first element of the array.
解法2: Binary Search

Java:

public int findDuplicate(int[] nums) {
    int slow = 0;
    int fast = 0;
 
    do{
        slow = nums[slow];
        fast = nums[nums[fast]];
    } while(slow != fast);
 
    int find = 0;
 
    while(find != slow){
        slow = nums[slow];
        find = nums[find];
    }
    return find;
} 

Java:

public int findDuplicate(int[] nums) {
    int l = 1,r = nums.length - 1;
    while(l < r){
        int m = (l + r) / 2;
        int c = 0;
  
        for(int i: nums){
            if(i <= m){
                c++;
            }
        }
  
        //if c < m,
        if(c > m){
            r = m;
        }else{
            l = m + 1;
        } 
    }
  
    return r;
}   

Python:

# Two pointers method
class Solution(object):
    def findDuplicate(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        slow = nums[0]
        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

Python:

# Time:  O(nlogn)
# Space: O(1)
# Binary search method.
class Solution(object):
    def findDuplicate(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        left, right = 1, len(nums) - 1

        while left <= right:
            mid = left + (right - left) / 2
            # Get count of num <= mid.
            count = 0
            for num in nums:
                if num <= mid:
                    count += 1
            if count > mid:
                right = mid - 1
            else:
                left = mid + 1
        return left

Python:

# Time:  O(n)
# Space: O(n)
class Solution(object):
    def findDuplicate(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        duplicate = 0
        # Mark the value as visited by negative.
        for num in nums:
            if nums[abs(num) - 1] > 0:
                nums[abs(num) - 1] *= -1
            else:
                duplicate = abs(num)
                break
        # Rollback the value.
        for num in nums:
            if nums[abs(num) - 1] < 0:
                nums[abs(num) - 1] *= -1
            else:
                break
        return duplicate  

C++:

class Solution {
public:
    int findDuplicate(vector<int>& nums) {
        int low = 1, high = nums.size() - 1;
        while (low < high) {
            int mid = low + (high - low) * 0.5;
            int cnt = 0;
            for (auto a : nums) {
                if (a <= mid) ++cnt;
            }
            if (cnt <= mid) low = mid + 1;
            else high = mid;
        }
        return low;
    }
};

C++:

class Solution {
public:
    int findDuplicate(vector<int>& nums) {
        int slow = 0, fast = 0, t = 0;
        while (true) {
            slow = nums[slow];
            fast = nums[nums[fast]];
            if (slow == fast) break;
        }
        while (true) {
            slow = nums[slow];
            t = nums[t];
            if (slow == t) break;
        }
        return slow;
    }
};

 

类似题目:

[LeetCode] 142. Linked List Cycle II 链表中的环 II

 

All LeetCode Questions List 题目汇总

 

 

 

以上是关于[LeetCode] 287. Find the Duplicate Number 寻找重复数的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 287. Find the Duplicate Number(找重复数字)

[LeetCode] 287. Find the Duplicate Number

LeetCode 287. Find the Duplicate Number

<LeetCode OJ> 287. Find the Duplicate Number

[LeetCode] 287. Find the Duplicate Number 寻找重复数

LeetCode 287. Find the Duplicate Number (找到重复的数字)