287. Find the Duplicate Number
Question
Total Accepted: 18097 Total
Submissions: 48596 Difficulty: Hard
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(1) extra space.
- 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.
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
Hide Tags
Array Two
Pointers Binary Search
Show Similar Problems
分析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]); } } };
以下为鉴赏别人的分析:
1). 使用快慢指针法,若链表中有环,可以得到两指针的交点M 2). 记链表的头节点为H,环的起点为E 2.1) L1为H到E的距离 2.2) L2为从E出发,首次到达M时的路程 2.3) C为环的周长 2.4) n为快慢指针首次相遇时,快指针在环中绕行的次数 根据L1,L2和C的定义,我们可以得到: 慢指针行进的距离为L1 + L2 快指针行进的距离为L1 + L2 + n * C 由于快慢指针行进的距离有2倍关系,因此: 2 * (L1+L2) = L1 + L2 + n * C => L1 + L2 = n * C => L1 = (n - 1)* C + (C - L2) 可以推出H到E的距离 = 从M出发绕环到达E时的路程 因此,当快慢指针在环中相遇时,我们再令一个慢指针从头节点出发 接下来当两个慢指针相遇时,即为E所在的位置
参考代码为:
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
时间: 2024-10-30 04:50:25