Two methods!!!! (recursive & iterative) Java, binary search


  • 0
    //recursive way
    public class Solution extends GuessGame {
        public int guessNumber(int n) {
            return cai(1,n);
        }    
        private int cai(int s, int e){
            int mid = s+(e-s)/2;
            //System.out.println(mid);
            if(guess(mid)==0) return mid;
            else if(guess(mid)>0) {mid=cai(mid+1,e);}
            else{mid = cai(s,mid);}
            return mid;
        }
    }
    
    //iterative way
    public class Solution extends GuessGame {
        public int guessNumber(int n) {
           int start = 1,end = n,mid=0;
           while(start <= end){
              mid= start+ (end-start)/2;  
              if(guess(mid)==0) return mid;
              if(guess(mid)>0) start = mid+1;
              else end = mid;
           }
           return mid;
        }
    }

Log in to reply
 

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