1. 程式人生 > >[LeetCode] 287. Find the Duplicate Number 尋找重復數

[LeetCode] 287. Find the Duplicate Number 尋找重復數

blank arc modify ini lba read href use rep

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

[LeetCode] 287. Find the Duplicate Number 尋找重復數