leetcode 035 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

题目大意:
给定一个排好序的整数数组nums,和一个数target,在排序数组中查找target,如果存在就返回位置下标;如果不存在就返回应该插入的位置,仍然保持数组nums有序。
例子如下:
[1,3,5,6], 5 → 2
[1,3,5,6], 2 → 1
[1,3,5,6], 7 → 4
[1,3,5,6], 0 → 0
从题目可知,插入位置即为数组中大于等于该数的最小的位置,将此问题转化为在数组中查找第一个大于等于该数的位置。由于该数组有序,因此可以使用二分查找。

可以先分析一下二分查找的过程:
当nums[middle] == target时,直接返回middle;nums[middle] > target时,再递归查找数组nums的左边一部分;nums[middle] < target时,再递归查找nums的右边一部分。

为了查找到第一个大于等于target,当nums[middle] >= target时,必须继续查找nums的左边部分,并且不能把nums[middle]排除在外(考虑到如果nums[middle]刚好时第一个大于等于target的情况);当nums[middle] < target时,可以按照二分查找,继续查找右边部分即可。
核心代码如下:

int searchInsertPosition(vector<int> &nums, int low, int up, 
                const int target) {
        if(low == up) return nums[low] >= target ? low : low + 1;

        int middle = (low + up) >> 1;
        if(nums[middle] >= target) 
        return searchInsertPosition(nums, low, middle, target);
        return searchInsertPosition(nums, middle + 1, up, target);
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值