Share my java solution


  • 0
    M
    public class Solution {
        public int searchInsert(int[] nums, int target) {
            if (nums == null) { return -1; }
            if (nums.length==0 || target<=nums[0]) { return 0; }
            if (target > nums[nums.length-1]) { return nums.length; }
            int left=0, right=nums.length-1;
            while (left < right-1) {
                int mid = left + (right-left)/2;
                if (target <= nums[mid]) { right = mid; }  // go left
                else { left = mid; }
            }  // post processing
            if (target <= nums[left]) { return left; }  // [2, 2]
            return right;  // [3, 4]
        }
    }

Log in to reply
 

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