C++ 8ms straightforward binary search method (easy to read)


  • 0
    W
    int searchInsertHelper(vector<int>& nums, int left, int right, int target)
    {
        if (left == right)
            return target <= nums.at(left) ? left : left + 1;
        
        int mid = (left + right) / 2;
        if (nums.at(mid) == target)
            return mid;
        else if (target < nums.at(mid))
            return searchInsertHelper(nums, left, mid, target);
        else
            return searchInsertHelper(nums, mid+1, right, target);
    }
    
    int searchInsert(vector<int>& nums, int target) 
    {
        if (nums.empty()) return 0;
        return searchInsertHelper(nums, 0, nums.size() - 1, target);
    }

Log in to reply
 

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