Java simple clean


  • 7
    J

    it looks very simple, but actually a little tricky. Have to pay attention to the detail.


    Algo. 1 --

      public int firstBadVersion(int n) {
        int lo = 1, hi = n;
        while (lo < hi) {
        	int med = lo + (hi -  lo)/2;
        	if (isBadVersion(med)) {
        		hi = med;
        	} else {
        		lo = med + 1;
        	}
        }
        return lo;
    }
    

    Algo.2 --

        public int firstBadVersion(int n) {
        int lo = 1, hi = n;
        while (lo <= hi) {
        	int med = lo + (hi -  lo)/2;
        	if (isBadVersion(med)) {
        		if (med == 1 || !isBadVersion(med-1))
        			return med;
        		hi = med;
        	} else {
        		lo = med + 1;
        	}
        }
        return -1; //no solution found.
    }

  • -2
    D
    public static int firstBadVersion1(int n) {
       if(n<=0)
        return -1;
    
        int i=0,j=0,k=0;
        i=0;
        k=n-1;
        while(true){
            j = ((k-i)/2) + i;
            if(isBadVersion(j) == true)
            {
                k=j;
            }else {
                i=j;
            }
            if(i==k || (k==(i+1) && isBadVersion(k) ==true))
            break;
        }
        return k;
    
    }

  • 0
    T

    Can you please expand on those "detail"?


Log in to reply
 

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