LeetCode287 — Find the Duplicate Number
阿新 • • 發佈:2019-02-02
題目: 找出一個重複的值,要去不能開闢空間,並且不能暴力解
思路:快慢指標,兩者相遇是在一個環中,而再依次遞增就在切面點相遇了。證明這裡省略(證明想了一上午,終於寫出來了)~
public class Solution287 { public int findDuplicate(int[] nums) { int slow = 0; int fast = 0; while (true){ slow = nums[slow]; fast = nums[nums[fast]]; if(slow == fast) break; } int point = 0; while(true){ slow = nums[slow]; point = nums[point]; if(slow == point){ return slow; } } } }