积少成多

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

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.

==============================

题目:如果把这个数组看做是链表,数组中元素值当做链表节点中next指针,

我们可以发现这道题就是在求 链表中环的  开始节点

有关环的开始节点证明,可以看这里:  [http://www.cnblogs.com/li-daphne/p/5551048.html]

=========

思路:利用fast/slow方法(slow的步长为1,fast的步长为2),找到"链表"相遇的地方,

这时候fast指向"链表"的开始位置,slow接着遍历(fast和slow的步长都为一).

当fast/slow再次相遇的地方,就是"链表环"的入口,即数组中 重复元素.

===========

代码:

class Solution {
public:
    int findDuplicate(vector<int>& nums) {
        if(nums.size()>1){
            int fast = nums[nums[0]];
            int slow = nums[0];
            while(slow!=fast){
                slow = nums[slow];
                fast = nums[nums[fast]];
            }

            fast = 0;
            while(fast != slow){
                fast = nums[fast];
                slow = nums[slow];
            }
            return slow;
        }
        return -1;
    }
};

 

posted on 2016-06-26 19:50  x7b5g  阅读(144)  评论(0编辑  收藏  举报