LeetCode 0035 - Search Insert Position
# Hints
- 二分查找
# 题面
Difficulty | Time Complexity Limit | Extra-Memory Complexity Limit |
---|---|---|
Easy |
Given a sorted array and a value, return the index if the 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.
Example 1:
Input: [1,3,5,6], 5
Output: 2
Example 2:
Input: [1,3,5,6], 2
Output: 1
Example 3:
Input: [1,3,5,6], 7
Output: 4
Example 4:
Input: [1,3,5,6], 0
Output: 0
# 题意
给定一个长为 的严格递增数组 ,给定一个整数 ,若 中存在 则返回其下标,否则返回其应当被插入到的位置的下标。
输入保证 中不存在重复元素。
# 题解
水题,二分查找即可。
# AC代码
class Solution {
public:
int searchInsert(vector<int> & nums, int target) {
// 二分查找
int index = lower_bound(nums.begin(), nums.end(), target) - nums.begin();
// 返回
return index;
}
};
- 01
- Reading Papers - Kernel Concurrency06-01
- 02
- Linux Kernel - Source Code Overview05-01
- 03
- Linux Kernel - Per-CPU Storage05-01