码迷,mamicode.com
首页 > 其他好文 > 详细

287. Find the Duplicate Number

时间:2017-06-08 13:02:33      阅读:155      评论:0      收藏:0      [点我收藏+]

标签:while   更改   exit   ber   runtime   integer   strong   遍历   ++   

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.

题目要求空间复杂度为O(1),也就是说不能使用Hash表算法。不能更改原序列,因此,原来交换位置的做法就行不通了。

进一步优化:面对如此有归可寻的序列,我们应当尽可能地想办法优化时间复杂度至O(nlogn)或O(n),蛮力算法的时间复杂度是O(n2)。

 

我们在区间[1, n]中搜索,首先求出中点mid,然后遍历整个数组,统计所有小于等于mid的数的个数,如果个数大于mid,则说明重复值在[mid+1, n]之间,反之,重复值应在[1, mid]之间,然后依次类推,直到区间长度变为1,此时的low就是我们要求的重复值。

class Solution {
public:
    int findDuplicate(vector<int>& nums) {
        int n = nums.size();
        
        if (n < 2)
            return 0;
        int low = 1;
        int high = n - 1;
        while (low < high) {
            int mid = (low + high) / 2;
            int count = 0;
            for (int i = 0; i < n; ++i) {
                if (nums[i] <= mid)
                    count++;
            }
            if (count <= mid)
                low = mid + 1;
            else
                high = mid;
        }
        return low;
    }
};

 

287. Find the Duplicate Number

标签:while   更改   exit   ber   runtime   integer   strong   遍历   ++   

原文地址:http://www.cnblogs.com/naivecoder/p/6962094.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!