Two different solutions in C++, both best submissions


  • 0

    One is binary search and the other is a cheating.

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

    class Solution {
    public:
        int searchInsert(vector<int>& nums, int target) 
        {
            return lower_bound(nums.begin(), nums.end(), target)-nums.begin();    
        }
    };

Log in to reply
 

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