O(log N) Binary search solution - straightfoward


  • 0
    K
    public int searchInsert(int[] nums, int target) {
        
        int lo = 0;
        int hi = nums.length-1;
        while (lo <= hi) {
            
            int mid = (lo + hi) >>> 1;
            int val = nums[mid];
            if (val == target) {
                return mid;
            }
            else if (target < val) {
                hi = mid-1;
            }
            else {
                lo = mid+1;
            }
        }
        
        return lo;
    }

Log in to reply
 

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