[One question per day] 35. Search the insertion position

Title: https://leetcode-cn.com/problems/search-insert-position/

Solution 1, Violent
O (n) O (1)
Pay attention to two conditions a. When there are no elements in the array b. The last element is not greater than the target

class Solution {
public:
    int searchInsert(vector<int>& nums, int target) {
        size_t i = 0;
        while (i < nums.size()) {
            if (nums[i] >= target) {
                return i;
            }
            i++;
        }
        return i == nums.size() ? i : -1;
    }
};

Solution 2, binary search
O (logn) O (1)
Note that the loop termination condition, the value of mid, and l + r may cross the boundary!

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

EOF

98 original articles have been published · 91 praises · 40,000+ views

Guess you like

Origin blog.csdn.net/Hanoi_ahoj/article/details/105376954