Simple Java solution using binary search


  • 0
    A
    public class Solution {
        public int searchInsert(int[] nums, int target) {
            if (nums == null || nums.length == 0){
                return 0;
            }
            int start = 0;
            int end = nums.length - 1;
            while (start < end){
                int mid = start + (end - start) /2;
                if (nums[mid] == target){
                    return mid;
                }
                else if (nums[mid] > target){
                    end = mid;
                }
                else {
                    start = mid + 1;
                }
            }
            if (target > nums[start]){
                return start + 1;
            }
            else {
                return start;
            }
        }
    }

Log in to reply
 

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