Binary Search Java Solution


  • 0
    C
    public int searchInsert(int[] nums, int target) {
            if(nums.length == 0 || nums == null) return 0;
            int len = nums.length;
            int left = 0;
            int right = len - 1;
            
            if(target > nums[nums.length - 1]) return nums.length;
            if(target < nums[0]) return 0;
            
            while(left < right) {
                int mid = (left + right)/2;
                if(target == nums[mid]) return mid; 
                if(target < nums[mid]) right = mid;
                else if (target > nums[mid]) left = mid + 1;
                
                if(right - left == 1 && target < nums[right] && target > nums[left]) return right;
            }
            return right;
        }
    

    any suggestion to improve?


Log in to reply
 

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