C++, 6ms


  • 0
    S
        int searchInsert(vector<int>& nums, int target) {
            int ret = -1;
            int lo = 0, hi = nums.size(), mid=-1;
            while (lo < hi) {
                mid = (lo + hi) / 2;
                if (nums[mid] < target)
                    lo = mid + 1;
                else if (nums[mid] > target)
                    hi = mid;
                else
                    break;
            }
            if(nums[mid] == target){
                ret = mid;
            }else if(nums[mid] > target){
                int k = mid-1;
                while(k>=0 && nums[k]>target)k--;
                if(k+1>=0 && nums[k+1]>target)ret=k+1;
            }else{
                int k = mid+1;
                while(k<nums.size() && nums[k]<target)k++;
                if(k-1<nums.size() && nums[k-1]<target)ret=k;
            }
            return ret;
        }
    
    

Log in to reply
 

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