题目:
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<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;
}
};其实这道题还有很多奇妙的解法:
版权声明:本文为博主原创文章,转载请联系我的新浪微博 @iamironyoung
【LeetCode从零单刷】Find the Duplicate Number
原文:http://blog.csdn.net/ironyoung/article/details/49018559