<LeetCode OJ> 287. Find the Duplicate Number
2016-01-27 09:53
239 查看
287. Find the Duplicate Number
My SubmissionsQuestion
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
相关文章推荐
- properties文件Eclipse中文乱码问题
- iOS开发--开发细节(去掉tableView下方的横线)
- [lintcode] - 391 Number of Airplanes in the Sky
- myeclipse svn信息突然消失
- Cocos2d-三维拾取Ray-AABB碰撞检测算法【转】
- python中类变量,成员变量
- JFreeChart生成饼图图片代码分享
- 用Excel函数简化批量导入AD用户及修改密码
- 人生 - 母亲的十年
- IOS中html5上传图片方向问题解决方法
- 安卓--第七天--fragment的实现
- spring 配置sqlite的方式
- scaleType属性的相关选项
- Spring多数据源事务解决方案
- Doc10(this,事件冒泡)
- mysql 触发器开荒
- Segmentation fault
- [土狗之路]coursera C语言基础12周(期末考试)作业
- STL STD::list使用说明
- Date.prototype.format,js下的时间格式处理函数