Solution sharing


  • 0
    W
    public class Solution {
    public int search(int[] A, int target) {
        int lo=0, hi=A.length-1;
        return newSearch(A, lo, hi, target);
    }
    private int newSearch(int[] A, int lo, int hi, int target){
        int mid=lo+(hi-lo)/2;
        int x1, x2;
        while(lo<=hi){         
            if(target==A[mid]) return mid;            
            else{
            //中间这一段容易引起边界溢出,注意注意
               if(hi<=mid+1) {
                   if (A[hi]==target)
                     return hi;
                   if(A[lo]==target)
                   return lo;
                   return -1;
               }
                x1=newSearch(A,lo,mid,target);
                x2=newSearch(A,mid,hi,target);               
                return Math.max(x1,x2);
            }            
        }
                return -1;
    }
    

    }


  • 0
    W

    sorry, just found out it is a silly O(N) time solution...


Log in to reply
 

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