Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ex29.java 压根就不需要跑就知道有问题,问题都没搞清楚 #14

Open
RealZark opened this issue May 17, 2020 · 3 comments

Comments

@RealZark
Copy link

No description provided.

@jimmysuncpt
Copy link
Owner

jimmysuncpt commented Jun 28, 2020

是 1.1.29 吗?请问具体问题是什么呢?@RealZark

@imyuewu
Copy link

imyuewu commented Jul 23, 2020

是 1.1.29 吗?请问具体问题是什么呢?@RealZark

1.1.29 rank是有问题的,比如你测试key为14,你返回的pos是-1,其实应该是 hi + 1;
另外1.1.29还可以优化,用while去逐个确认是否相等,效率比较低,可以继续用二分查找的思路去查相等的值。

@imyuewu
Copy link

imyuewu commented Jul 23, 2020

这个应该是一个正确的解,但是不是最优解

public static int rank(int[] a, int key) {
    int lo = 0;
    int hi = a.length - 1;
    
    while (lo <= hi) {
        int mid = lo + (hi - lo) / 2;
        if (a[mid] > key) {
            hi = mid - 1;
        } else if (a[mid] < key) {
            lo = mid + 1;
        } else {
            // find, look backward
            --mid;
            while (mid >= lo && a[mid] == key) {
                --mid;
            }
            return mid + 1;
        }
    }
    // not found
    return hi + 1;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants