【LeetCode從零單刷】Find the Duplicate Number
阿新 • • 發佈:2019-01-31
題目:
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:
- You must not modify the array (assume the array is read only).
- You must use only constant, O
- Your runtime complexity should be less than
O(n2)
. - 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; } };
- 二分法:遍歷一遍陣列,大於中間數的個數如果多於 (n / 2) 則說明多出來的數在大於中間數的那部分中,同理也可能在小於中間數的那部分中。這樣每次只關注某一半的資料,搜尋一半而已;
- 對映找環法:使用快慢兩個指標遍歷,非常巧妙