Leetcode - H-Index II

My code:

public class Solution {
    public int hIndex(int[] citations) {
        int n = citations.length;
        int begin = 0;
        int end = n - 1;
        while (begin <= end) {
            int mid = begin + (end - begin) / 2;
            if (citations[mid] > n - mid) {
                end = mid - 1;
            }
            else if (citations[mid] < n - mid) {
                begin = mid + 1;
            }
            else {
                begin = mid;
                break;
            }
        }
        return n - begin;
    }
}

用 Binary search 找最接近target并且 >= target 的 那个index
果然还是很常用的算法,一定要记住。

Anyway, Good luck, Richardo! — 09/21/2016

    原文作者:Richardo92
    原文地址: https://www.jianshu.com/p/f52c96d1fab5#comments
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞