0ms O(logn) solution C++ for insert position


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

Log in to reply
 

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