題目:
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:
O(n2).
解答:
其實我第一個想法就是排序,如果前後相同就說明元素重復了。滿足上面的所有要求,然後AC了……
class Solution {
public:
int findDuplicate(vector& 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) 則說明多出來的數在大於中間數的那部分中,同理也可能在小於中間數的那部分中。這樣每次只關注某一半的數據,搜索一半而已;映射找環法:使用快慢兩個指針遍歷,非常巧妙 以上兩種解法具體見:傳送門