zoukankan      html  css  js  c++  java
  • 275. H-Index II

    题目:

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

    Hint:

    1. Expected runtime complexity is in O(log n) and the input is sorted.

    链接: http://leetcode.com/problems/h-index-ii/

    题解:

    假如给定数组是排序好的,求H-Index。 我们就可以用Binary Search。 target = len - mid。

    Time Complexity - O(logn), Space Complexity - O(1)

    public class Solution {
        public int hIndex(int[] citations) {
            if(citations == null || citations.length == 0) {
                return 0;
            }
            int len = citations.length, lo = 0, hi = len - 1;
            
            while(lo <= hi) {
                int mid = lo + (hi - lo) / 2;
                if(citations[mid] == len - mid) {
                    return citations[mid];
                } else if(citations[mid] > (len - mid)) {
                    hi = mid - 1;
                } else {
                    lo = mid + 1;
                }
            }
            
            return len - lo;
        }
    }

    题外话: 房子的装修师傅今天离开了,但是关键的电炉灶没接好,原因是总闸处220v电线有问题,导致插座没电。不过都是熟人,我也不想他们碰处一些危险的东西。虽然还要另找电工检查线路和接线,很费事费钱,但我想明年争取换份好工作,挣回来就好了。

    二刷:

    对于在位置i的论文来说, 至少len - i的论文, citations数目都比位置i的论文大。所以i位置的h-index至少是len - i。我们就可以用Binary Search来搜索答案。

    Java:

    public class Solution {
        public int hIndex(int[] citations) {
            if (citations == null || citations.length == 0) {
                return 0;
            }
            int len = citations.length, lo = 0, hi = len - 1;
            while (lo <= hi) {
                int mid = lo + (hi - lo) / 2;
                if (citations[mid] == len - mid) {
                    return citations[mid];
                } else if (citations[mid] < len - mid) {
                    lo = mid + 1;
                } else {
                    hi = mid - 1;
                }
            }
            return len - lo;
        }
    }

    Reference:

    https://leetcode.com/discuss/56122/standard-binary-search

    https://leetcode.com/discuss/56170/java-binary-search-simple-and-clean

  • 相关阅读:
    Vue路由配置
    vue项目 favicon.ico不显示解决方案
    Vux使用AjaxPlugin发送请求跨域问题解决
    改变vux样式,自定义样式
    Hive LLAP
    GitHub提交代码无contributions记录解决办法
    Java websocket+ nginx+redis负载均衡上实现单对单通讯
    springboot异步接口
    C#中$的用法(转载)
    vmware-tools灰色而无法安装的问题
  • 原文地址:https://www.cnblogs.com/yrbbest/p/5032078.html
Copyright © 2011-2022 走看看