Using binary search in Java


  • 0
    W
    public class Solution {
        public int hIndex(int[] citations) {
            int[]c=citations;
            int l=0,r=c.length-1;
            int e=c.length;
            while(l<=r){
                int m=(l+r)/2;
                if(c[m]>=c.length-1-m+1){
                    //if its left element(if any) is no more than e-m then it'll be fine.
                    if(m-1<0||c[m-1]<=e-m)return e-m;
                    else r=m-1;
                } else {
                    l=m+1;
                }
                
            }
            return 0;
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.