Standard binary search template maybe better than other posts


  • 3

    start stores the in-valid position, end stores the biggest valid position.

      (start, end] 
    

    Code:

       class Solution {
        public:
            int searchInsert(vector<int>& nums, int target) {
                if(nums.size()==0)  return 0;
                int start=-1, end=nums.size();
                
                while(end-start>1){
                    int mid=(start+end)/2;
                    if(target <= nums[mid]) end=mid;
                    else  start=mid;
                }
                return end;
            }
        };

  • 0
    A

    You can get rid of the if(nums.size() == 0 ) check


Log in to reply
 

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