H-Index II

题目
Follow up for H-Index: What if the citations array is sorted in ascending order? Could you optimize your algorithm?

答案

class Solution {
    public int hIndex(int[] citations) {
        int left = 0, right = citations.length - 1, max = 0;
        while(left <= right) {
            int mid = left + (right - left) / 2;
            if(citations[mid] >= (citations.length -1 - mid + 1)) {
                max = Math.max(max, (citations.length -1 - mid + 1)); // Go Left
                right = mid - 1;
            }
            else
                left = mid + 1; // Go right
        }
        return max;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。