LeetCode 35. Search Insert Position

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);
    }
};
全部评论

相关推荐

09-01 11:31
门头沟学院 Java
buul:七牛云的吧,感觉想法是好的,但是大家没那么多时间弄他这个啊。。。不知道的还以为他是顶尖大厂呢还搞比赛抢hc,只能说应试者的痛苦考察方是无法理解的,他们只会想一出是一出
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务