Leetcode——Array 3
来源:互联网 发布:手机逛淘宝费流量吗 编辑:程序博客网 时间:2024/06/10 14:27
Find the Duplicate Number
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.
思路:
该题和Array 2 最大的不同点在于不能在原来的数组上进行修改,于是第一反应是回归原思路,创建一个相同的数组,然后排序,判断临近位相等的位置。今天看到大神做法,因为存在一个重复的数字,所以从链表的角度来看的话,部分节点会形成一个闭合,因此创建一个慢指针,一个快指针,慢指针 slow = nums[slow]; fast = nums[nums[fast]];
两个指针会在circle相遇。之后的另一个while循环不知理解是否正确,因为第一个循环里面fast走了2*path和慢指针的path相遇,因此第二个循环里慢指针再走path将和从头开始的指针相遇。(这样解释会觉得两个path是一样的,这是因为起点不同nums[0] vs 0?)
大神代码实现如下:
public class Solution { public int findDuplicate(int[] nums) { int slow = nums[0]; int fast = nums[nums[0]]; while(fast != slow){ slow = nums[slow]; fast = nums[nums[fast]]; } fast = 0; while(fast != slow){ // still don't get why they will definitely meet slow = nums[slow]; fast = nums[fast]; } return slow; }}
- Leetcode——Array 3
- LeetCode——Rotate Array
- Leetcode——Array 2
- 【leetcode】Array——Rotate Array(189)
- leetcode小记3——array,string(238,242)
- 【leetcode】Array——3Sum Closest(16)
- Leetcode学习(3)—— Array Partition I
- LeetCode——Merge Sorted Array
- LeetCode——Merge Sorted Array
- LeetCode——Merge Sorted Array
- Merge Sorted Array —— Leetcode
- LeetCode——Merge Sorted Array
- LeetCode题解——Merge Sorted Array
- leetcode 088 —— Merge Sorted Array
- LeetCode题解——Rotate Array
- leetcode 88 ——Merge Sorted Array
- 【leetcode】Array——word search(79)
- 【leetcode】Array——Triangle(120)
- 线性表(插入/清除数据/快慢指针查找中间数据)
- 《算法导论》堆排序和优先队列
- 常用polyfill代码
- POJ 2699 The Maximum Number of Strong Kings(枚举+最大流)
- Lua + GraphicsMagick安装
- Leetcode——Array 3
- (.vmx)修复方法
- Problem B: STL——管道一
- 《算法导论》线性时间O(n)排序
- 欢迎使用CSDN-markdown编辑器
- Robot Framework IE11 Selenium2Library 找不到窗口 找不到对象 找不到元素 注册表
- android学习(二十一) 下载数据减少电池损耗
- 《算法导论》选择问题(找第K大的数)
- Problem A: STL——管道二