【leetcode】Array——Find the Duplicate Number(287)

題目:

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).
  4. There is only one duplicate number in the array, but it could be repeated more than once.

思路:該題想了很久不會寫 T^T 哎…還是自己太渣了,看了leetcode大神的思路

這道題和leetcode另一道題:找 Linked List Cycle 入口是一個原理 https://leetcode.com/problems/linked-list-cycle-ii/ https://leetcode.com/problems/linked-list-cycle-ii/ https://leetcode.com/problems/linked-list-cycle-ii/

兩個指正,slow和fast。slow每次跳一個,fast每次跳2個,當fast和slow相遇時,fast比slow多走了至少一個circle,且相遇在circle內部。

相遇的位置距離circle入口 和 起點到入口的距離相等。(可以證明的。)

然後讓其中一個指針(fast)回到原點,每次跳1個,slow繼續從之前和fast相遇的地點出發,每次跳1個,最終兩個會在入口處相遇。

circle入口在本題中就是重複的元素。

代碼:

    public int findDuplicate(int[] nums) {
    	int slow = nums[0];
    	int fast = nums[nums[0]];
    	
    	while(slow!=fast){
    		slow = nums[slow];
    		fast = nums[nums[fast]];
    	}
    	
    	fast = 0;
    	while(slow!=fast){
    		slow = nums[slow];
    		fast = nums[fast];
    	}
    	return slow;
        
    } 

leetcode大神給的答案:https://leetcode.com/discuss/61514/understood-solution-space-without-modifying-explanation
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章