1. 程式人生 > >【LeetCode從零單刷】Find the Duplicate Number

【LeetCode從零單刷】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.

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.

解答:

其實我第一個想法就是排序,如果前後相同就說明元素重複了。滿足上面的所有要求,然後AC了……

class Solution {
public:
    int findDuplicate(vector<int>& nums) {
        sort(nums.begin(), nums.end());
        int ans = nums[0];
        for(int i = 0; i< nums.size() - 1; i++)
        {
            if(nums[i] == nums[i+1])    ans = nums[i];
        }
        return ans;
    }
};
其實這道題還有很多奇妙的解法:
  1. 二分法:遍歷一遍陣列,大於中間數的個數如果多於 (n / 2) 則說明多出來的數在大於中間數的那部分中,同理也可能在小於中間數的那部分中。這樣每次只關注某一半的資料,搜尋一半而已;
  2. 對映找環法:使用快慢兩個指標遍歷,非常巧妙
以上兩種解法具體見:傳送門