【leetcode】35. Search Insert Position 给定数字插入有序数组的下标点

1. 题目

Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.code

You may assume no duplicates in the array.get

Here are few examples.
[1,3,5,6], 5 → 2
[1,3,5,6], 2 → 1
[1,3,5,6], 7 → 4
[1,3,5,6], 0 → 0it

2. 思路

二分查找第一个大于等于的位置。io

3. 代码

耗时:9msclass

class Solution {
public:
    int searchInsert(vector<int>& nums, int target) {
        return bsearch(nums, 0, nums.size(), target);
    }
    
    int bsearch(vector<int>& nums, int i, int j, int target) {
        if (i >= j) return i;
        if (i+1 == j) { return nums[i] < target ? i+1 : i;}
        int k = i + (j - i) / 2;
        int vk = nums[k];
        if (vk == target) {
            return k;
        } else if (vk > target) {
            return bsearch(nums, i, k, target);
        } else {
            return bsearch(nums, k+1, j, target);
        }
    }
};
相关文章
相关标签/搜索