Java simplest solution only 2 lines


  • 1
    Y

    The simplest way is to use Arrays.binarySearch

        public int searchInsert(int[] nums, int target) {
            int i = Arrays.binarySearch(nums, target);
            return i >= 0 ? i : ~i;
        }
    

    If we steal the code from Arrays.binarySearch then the implementation is as follows:

        public int searchInsert(int[] nums, int target) {
            int l = 0, h = nums.length - 1;
            while (l <= h) {
                int mid = (l + h) >>> 1;
                if (target == nums[mid]) return mid;
                else if (target < nums[mid]) h = mid - 1;
                else l = mid + 1;
            }
            return l;
        }
    

Log in to reply
 

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