标签:
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).Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
分析1:
本题提示为双指针问题,不知道怎么做!!!
本人的,不符合要求的做法,有空间复杂度!
class Solution {
public:
int findDuplicate(vector<int>& nums) {
unordered_set<int> uset;
for (int i =0;i < nums.size(); i++)
{
if(uset.find(nums[i])!=uset.end())
return nums[i];
else
uset.insert(nums[i]);
}
}
};以下为鉴赏别人的分析:
参考代码为:
class Solution {
public:
int findDuplicate(vector<int>& nums) {
int slow = nums[0], fast = nums[nums[0]];
while(slow != fast) {
slow = nums[slow];
fast = nums[nums[fast]];
}
slow = 0;
while(slow != fast) {
slow = nums[slow];
fast = nums[fast];
}
return slow;
}
};
注:本博文为EbowTang原创,后续可能继续更新本文。如果转载,请务必复制本条信息!
原文地址:http://blog.csdn.net/ebowtang/article/details/50569543
原作者博客:http://blog.csdn.net/ebowtang
<LeetCode OJ> 287. Find the Duplicate Number
标签:
原文地址:http://blog.csdn.net/ebowtang/article/details/50569543