274. H-Index, 275. H-Index II

274 就先sort一下,再遍历一遍
从高到低排序,
然后从左向右扫。如果一个数的值大于等于他的index + 1,则更新h index为 index + 1, 否则退出。

这题可以用binary Search写

public int hIndex(int[] citations) {
        //0 1 3 4 5 6 6 8
        if (citations.length == 0) return 0;
        //looking for last place where there are n paper left and the citations >= n
        Arrays.sort(citations);  
        int N = citations.length;
        int l = 0, r = N - 1;
        while (l < r) {
            int m = l + (r - l) / 2;
            int numberOfPaper = N - m;
            if (citations[m] < numberOfPaper) {
                l = m + 1; // must be a smaller number of Paper
            } else if (citations[m] > numberOfPaper) {
                r = m; //m could be a right ans, should not miss it.
            } else if (numberOfPaper == citations[m]) {
                return numberOfPaper; //
            }
        }
        return Math.min(N - l, citations[l]);
    }
class Solution {
    public int hIndex(int[] citations) {
        Arrays.sort(citations);
        int l = 0, r = citations.length - 1;
        while (l < r) {
            swap(citations, l++, r--);
        }
        int max = 0;
        for (int i = 0; i < citations.length; i++) {
            if (citations[i] >= i + 1) {
                max = i + 1;
            } else {
                break;
            }
        }
        return max;
    }
    private void swap(int[] citations, int i, int j) {
        int tmp = citations[i];
        citations[i] = citations[j];
        citations[j] = tmp;
    }

}
  1. H-Index II
    这题可以用binary search做,
    他的termination 条件比较新鲜。
    public int hIndex(int[] citations) {
        int N = citations.length;
        if (N == 0) return 0;
        int l = 0, r = N - 1;
        int ans = 0;
        while ( l <= r) { //肯定可以退出循环
            int m = l + (r - l) / 2;
            if (citations[m] >= N - m) {
                r = m - 1; //不会漏掉解,因为我更新了 
                ans = N - m; //可以更新
            } else {
                l = m + 1; //不可以更新 
            }
        }
        return ans;
    }

C++ version

class Solution {
public:
    int hIndex(vector& citations) {
        if (citations.size() == 0) return 0;
        int l = 0, r = citations.size() - 1;
        int sz = citations.size();
        while (l < r) {
            int m = l + (r - l) / 2;
            int n = sz - m;
            if (n == citations[m]) {
                return n;
            } else if (n < citations[m]) {
                r = m;
            } else {
                l = m + 1;
            }
        }
        return min(citations[l], sz - l);
    }
};

你可能感兴趣的:(274. H-Index, 275. H-Index II)