General way of forming Binary Search, my 5ms solution


  • 0
    K

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


  • 0
    X

    so nice!!! how could you come up with such a smart solution!


Log in to reply
 

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