Binary Search


  • 0
    public int search(int[] nums, int target) {
            int start=0, end=nums.length-1;
            int mid=start+(end-start)/2;
            while(start<end){
                if(nums[mid]==target) { return mid; }
                if(nums[start]==target){ return start;}
                if(nums[end]==target){return end;}
                if(nums[mid]>nums[start]&&nums[mid]<target){
                    start=mid+1;
                }else if(nums[mid]<nums[start]&&nums[mid]>target){
                    end=mid;
                }else if(nums[mid]>nums[start]&&nums[mid]>target){
                    if(target>nums[start]) { end=mid; }
                    else { start=mid+1; }
                }else{
                    if(target<nums[start]) { start=mid+1; }
                    else { end=mid; }
                }
                mid=start+(end-start)/2;
            }
            if(nums[start]==target){ return start;}
            return -1;
        }
    

Log in to reply
 

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