Find the Duplicate Number(Leetcode 287)

<h1 style="box-sizing: border-box; margin: 0.5em 0px 25px; font-size: 20px; line-height: 1.1em; color: rgb(68, 68, 68); border-bottom-width: 1px; border-bottom-style: solid; border-bottom-color: rgb(221, 221, 221); position: relative; padding: 14px 25px 5px 0px;"><span class="entry-title" style="box-sizing: border-box; color: rgb(0, 0, 0);">Java O(1)space using Binary-Search</span></h1>
public int findDuplicate(int[] nums) {
    int low = 1, high = nums.length - 1;
    while (low <= high) {
        int mid = (int) (low + (high - low) * 0.5);
        int cnt = 0;
        for (int a : nums) {
            if (a <= mid) ++cnt;
        }
        if (cnt <= mid) low = mid + 1;
        else high = mid - 1;
    }
    return low;
}

原发布地址点击打开链接


some problems:

This does not fly since you assume that the count of elements on one side of mid will be enough to tell you where the repeated element is. This is not always the case. Consider:

0 1 2 2 2 5 6 7 8 9 10. mid is 5 and the count on either side is unchanged by the repeated element. You still need to inspect both segments.


I think he used binary-search method, but the complexity is O(n) rather than O(logn). However, it is still a pretty good algorithm which I can not work out by myself. :-(


Regardless. Binary search in this way will not work since counting member on either side of the mid-point is not sufficient to determine where the repeat number is. Modified example 1 2 2 2 5 6 7 8 9 10 11 2 is repeated 2 more times. midpoint is 6. count is 5 on both sides of the midpoint. count cannot differentiate where the repeat number is.


This does not fly since you assume that the count of elements on one side of mid will be enough to tell you where the repeated element is. This is not always the case. Consider: 1 2 2 2 5 6 7 8 9 10 11. mid is 6 and the count on either side is unchanged by the repeated element. You still need to inspect both segments.


posted @ 2015-11-29 22:32  窗外临街  阅读(166)  评论(0编辑  收藏  举报