LeetCode: 35. Search Insert Position

题目描述

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

大意就是说: 给一个数组和待查找的元素。 要是数组中存在该元素, 则找到它的下标, 否则找到它应该插入的位置。

解题思路

利用二分查找的思路, 只需要在查找失败时 返回当前下标。

AC源码

class Solution {
public:
    int bsearch(vector<int>& nums, int left, int right, int target)
    {
        if(left >= right) return left;
        int mid = (left + right)/2;
        if(nums[mid] == target) return mid;
        else if(nums[mid] < target) return bsearch(nums, mid+1, right, target);
        else return bsearch(nums, left, mid, target);
    }
    int searchInsert(vector<int>& nums, int target) {
        return bsearch(nums,0,nums.size(),target);
    }
};