zoukankan      html  css  js  c++  java
  • [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 题目汇总

  • 相关阅读:
    C#刷遍Leetcode系列连载 索引
    C#刷遍Leetcode面试题系列连载(2): No.38
    C#刷遍Leetcode面试题系列连载(1)
    Windows新终端中玩转ASCII和Emoji游戏的正确姿势
    终于等到你!微软正式上线 Windows Terminal 预览版
    任意公众号的文中插入外链的方法找到了,亲测有效
    只需3步,即可将你的Chromium Edge 浏览器设置成中文
    重磅福利 | 知乎上赞同数最高的1000个回答2019最新版
    黑科技抢先尝(续)
    GitHub上最火爆!码代码不得不知的所有定律法则
  • 原文地址:https://www.cnblogs.com/lightwindy/p/9602295.html
Copyright © 2011-2022 走看看