2016年2月10日 星期三

LEET code -- 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:


  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.

這題要利用link list cycle II 的解法
因為這個陣列只包含1~n  
所以可以看成是圖型   第0個點 下一點要去哪




 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
int findDuplicate(int* nums, int numsSize) {
    //like link list cycle
    int slow=0,fast=0;
    while(true){
        int slowindex=slow,fastindex=fast;
        slow=nums[slowindex];
        fast=nums[nums[fastindex]];
        //printf("A%d %d,%d %dA",slow,slowindex,fast,fastindex);
        if(slow==fast)break;
    }
    int find=0;
    while(true){
        find = nums[find];
        slow = nums[slow];
        if(find==slow)return find;
    }
}

沒有留言:

張貼留言