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

相关推荐

不愿透露姓名的神秘牛友
04-25 10:45
点赞 评论 收藏
分享
每晚夜里独自颤抖:你cet6就cet6,cet4就cet4,你写个cet证书等是什么意思。专业技能快赶上项目行数,你做的这2个项目哪里能提现你有这么多技能呢
点赞 评论 收藏
分享
06-19 12:33
安徽大学 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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