A simple Binary search


  • 0
    L

    It is a basic binary search problem and one needs to keep track of the start index to mark the position that is the right one for a missing number.

    public int searchInsert(int[] nums, int target) {
            if(nums==null || nums.length==0) {
                return -1;
            }
            
            int s = 0;
            int e = nums.length-1;
            while(s<=e) {
                int p = (e-s)/2 + s;   
                
                if(nums[p]==target) {
                    return p;
                }
                else if(nums[p]>target) {
                    e = p-1;
                }
                else {
                    s = p+1;
                }
            }
            
            return s;
        }
    

Log in to reply
 

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