Beats 99.48% cpp submissions


  • 0
    I
    class Solution {
    public:
        int searchInsert(vector<int>& nums, int target) {
            return myBinarySearch(nums, 0, nums.size() - 1, target);
        }
        int myBinarySearch(vector<int>& nums, int start, int end, int target) {
            if (target < nums.at(start)) return 0;
            if (target > nums.at(end)) return end + 1;
            while (start <= end) {
                //cout << start << " " << end << endl;
                if (start == end) {
                    return end;
                }
                int mid = start + (end - start) / 2;
                if (nums.at(mid) > target) {
                    end = mid;
                }
                else if (nums.at(mid) < target) {
                    start = mid + 1;
                }
                else {
                    return mid;
                }
            }
            return -1;
        }
    };
    

Log in to reply
 

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