【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.

You may assume no duplicates in the array.

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 → 0

2. 思路

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

3. 代码

耗时:9ms

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);
        }
    }
};
    原文作者:knzeus
    原文地址: https://segmentfault.com/a/1190000007287526
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞