287. Find the Duplicate Number

来源:互联网 发布:网络教育和电大区别 编辑:程序博客网 时间:2024/04/30 00:13

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).

  1. There is only one duplicate number in the array, but it could be repeated more than once.

我没答上来,都是别人的优秀的答案。
1. 二分查找 
对[1,n]中,取mid,然后从数组中找小于等于mid的个数,若个数小于等于mid,说明重复值不在[1,mid]中,因此将范围移至[mid+1,n];若个数大于mid,说明重复值在[1,mid]中
注意,正确的二分查找的范围是
[a,b) 一个开区间,一个闭区间,则循环下次为闭区间的则mid为t=a+1; 开区间的则为t=b


代码:
class Solution {public:    int findDuplicate(vector<int>& nums) {        int b = 1, e = nums.size()-1,m = 0;        while(b < e){            m = b + (e - b)/2;            int count = 0;            for(int i = 0; i < nums.size(); i++)            if(nums[i] <= m)            ++count;            if(count <= m)             b = m + 1;             else             e = m;        }        if((b>0) && b <nums.size())        return b;        else         return -1;    }};

2.用类似链表中的有环来做
The main idea is the same with problem Linked List Cycle II,https://leetcode.com/problems/linked-list-cycle-ii/. Use two pointers the fast and the slow. The fast one goes forward two steps each time, while the slow one goes only step each time. They must meet the same item when slow==fast. In fact, they meet in a circle, the duplicate number must be the entry point of the circle when visiting the array from nums[0]. Next we just need to find the entry point. We use a point(we can use the fast one before) to visit form begining with one step each time, do the same job to slow. When fast==slow, they meet at the entry point of the circle. The easy understood code is as follows.

int findDuplicate3(vector<int>& nums){    if (nums.size() > 1)    {        int slow = nums[0];        int fast = nums[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;}


0 0
原创粉丝点击