Binary search solution in java


  • 0
    P
    class Solution {
        public int searchInsert(int[] nums, int target) {
            int i=0, j=nums.length-1,mid = (nums.length-1)/2;      
            
            if(nums.length==1) {
                if(target>nums[0]) return nums.length;
                else if(target<nums[0]||target==nums[0]) return 0;
            } 
            
            int result = binarySearch(nums,0,nums.length-1,target);
            
            if(result==-1){
    
                while(i<=j) {
                    if(target<nums[i]) return i;
                    if(target>nums[j]) return j+1;
                    if(i+1==j) return j;
                    i++;
                    j--;
                }
    
            }
     
            return result;
        }
        
            int binarySearch(int arr[], int l, int r, int x)
        {
            if (r>=l)
            {
                int mid = l + (r - l)/2;
     
                if (arr[mid] == x)
                   return mid;
    
                if (arr[mid] > x)
                   return binarySearch(arr, l, mid-1, x);
    
                return binarySearch(arr, mid+1, r, x);
            }
            return -1;
        }
        
    }
    

Log in to reply
 

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