Find the Duplicate Number
来源:互联网 发布:sql 按月分组 编辑:程序博客网 时间:2024/05/29 16:35
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:
1、You must not modify the array (assume the array is read only).
2、You must use only constant, O(1) extra space.
3、Your runtime complexity should be less than O(n2).
Note:
1、You must not modify the array (assume the array is read only).
2、You must use only constant, O(1) extra space.
3、Your runtime complexity should be less than O(n2).
4、There is only one duplicate number in the array, but it could be repeated more than once.
使用映射找环法:
int findDuplicate(int* nums, int numsSize) { int slow = 0; int fast = 0; do { slow = nums[slow]; fast = nums[nums[fast]]; }while(slow != fast); int find = 0; while(slow != find) { slow = nums[slow]; find = nums[find]; } return find;}数学分析:
如图,快慢指针同时从O点出发,慢指针每次移动一个单位,快指针每次移动两个单位,则在相遇点n,慢指针移动n个单位,快指针移动2n个单位。
那么问题就简单了:如果给一个指针find从头开始移动n个单位,和慢指针移动n个单位的结果就是又在n点相遇,但是m--->n点经过的点是完全一样的,所以第一次相遇的点就是环的起始点。
0 0
- Find the Duplicate Number
- Find the Duplicate Number
- Find the Duplicate Number
- Find the Duplicate Number
- Find the Duplicate Number
- Find the Duplicate Number
- Find the Duplicate Number
- Find the Duplicate Number
- Find the Duplicate Number
- Find the Duplicate Number
- Find the Duplicate Number
- Find The Duplicate Number
- Find the Duplicate Number
- Find the Duplicate Number
- Find the Duplicate Number
- Find the Duplicate Number
- Find the Duplicate Number
- Find the Duplicate Number
- Dialog throwing "Unable to add window — token null is not for an application” with getApplication()
- ThreadPoolExecutor使用和思考-线程池大小设置与BlockingQueue的三种实现区别
- group_concat的用法 及注意点
- linux lvm 简介之二 扩充空间
- 网络服务调用总结
- Find the Duplicate Number
- 86. Partition List
- esayui 中的 load,reload,loadData的区别
- Tips
- iOS后台运行定时器
- POJ1426 建议打表做该题/用数组模拟队列(比STL队列速度要快)
- 2016-5-18-1
- RecyclerView CardView使用解析
- SDWebImage的内部原理、实现机制以及优化方式