【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);
        }
    }
};
相關文章
相關標籤/搜索