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

LeetCode "Find the Duplicate Number"

时间:2015-09-30 00:54:45      阅读:164      评论:0      收藏:0      [点我收藏+]

标签:

Catch the sparkle: if only one number is duplicated in [1..n], all following numbers will be "shifted" right.

class Solution {
public:
    int findDuplicate(vector<int>& nums) {
        int np = nums.size();
        int n = np - 1;
        
        int s = 1, e = n;
        while(s<e)
        {
            int mid = (s + e) / 2;
            int cnt = 0;
            for(auto v : nums)
                if(v <= mid) cnt++;
            if(cnt >mid)
            {
                e = mid;
            }
            else
            {
                s= mid + 1;
            }
        }
        return s;
    }
};

And yes, there is a smarter solution: http://keithschwarz.com/interesting/code/?dir=find-duplicate

LeetCode "Find the Duplicate Number"

标签:

原文地址:http://www.cnblogs.com/tonix/p/4847633.html

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