首页 > 其他 > 详细

LeetCode "Find the Duplicate Number"

时间:2015-09-30 00:52:43      阅读:673      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!