Easy to understand 8ms binary search log(n) solution


  • 0
    G
      int searchInsert(vector<int>& nums, int target) {
                    int l=0,r=nums.size()-1,mid=0;
                    if(r>=0 && nums[r]<target) return r+1;
                    while(r>l)
                    {
                        mid=(r-l)/2+l;
                        if(nums[mid]>target) r=mid-1;
                        else if(nums[mid]<target)l=mid+1;
                        else return mid;
                    }
                    
                    if(nums[l]>=target) return l;
                    return l+1;
        }

Log in to reply
 

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