[LeetCode] 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

这道题基本没有什么难度,实在不理解为啥还是Medium难度的,完完全全的应该是Easy啊,三行代码搞定的题,只需要遍历一遍原数组,若当前数字大于或等于目标值,则返回当前坐标,如果遍历结束了,说明目标值比数组中任何一个数都要大,则返回数组长度n即可,代码如下:

解法一:

class Solution {
public:
    int searchInsert(vector<int>& nums, int target) {
        for (int i = 0; i < nums.size(); ++i) {
            if (nums[i] >= target) return i;
        }
        return nums.size();
    }
};

当然,我们还可以用二分搜索法来优化我们的时间复杂度,而且个人认为这种方法应该是面试官们想要考察的算法吧,参见代码如下:

解法二:

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

本文转自博客园Grandyang的博客,原文链接:搜索插入位置[LeetCode] Search Insert Position ,如需转载请自行联系原博主。

相关文章
|
1月前
|
算法
力扣240 搜索二维矩阵II
力扣240 搜索二维矩阵II
|
3月前
|
Go
golang力扣leetcode 240.搜索二维矩阵II
golang力扣leetcode 240.搜索二维矩阵II
19 0
|
3月前
|
Go
golang力扣leetcode 79.单词搜索
golang力扣leetcode 79.单词搜索
25 0
|
3月前
|
算法
【Leetcode 74】搜索二维矩阵 —— 二分查找|矩阵
给你一个满足下述两条属性的`m x n`整数矩阵:每行中的整数从左到右按非严格递增顺序排列。每行的第一个整数大于前一行的最后一个整数
|
3月前
|
Go
golang力扣leetcode 81.搜索旋转排序数组II
golang力扣leetcode 81.搜索旋转排序数组II
17 0
|
3月前
|
Go
golang力扣leetcode 33.搜索旋转排序数组
golang力扣leetcode 33.搜索旋转排序数组
14 0
|
3月前
|
Go
golang力扣leetcode 74.搜索二维矩阵
golang力扣leetcode 74.搜索二维矩阵
18 0
|
3月前
|
Go
golang力扣leetcode 35.搜索插入位置
golang力扣leetcode 35.搜索插入位置
15 0
|
3月前
|
Go
golang力扣leetcode 61.搜索区间
golang力扣leetcode 61.搜索区间
18 0
|
4月前
|
存储 算法 vr&ar
☆打卡算法☆LeetCode 212. 单词搜索 II 算法解析
☆打卡算法☆LeetCode 212. 单词搜索 II 算法解析
☆打卡算法☆LeetCode 212. 单词搜索 II 算法解析