二分查找 lower_bound,返回第一个 ≥ target 的位置,即插入位置。
OJ: leetcodecn
题目 ID: search-insert-position
难度:普及-
标签:二分查找数组
日期: 2026-07-29 11:45
题意
给定升序无重复数组 nums 和目标值 target,返回 target 在数组中的索引;若不存在,返回按顺序插入的位置。要求
思路
本题本质是求 lower_bound:区间内第一个 lower_bound;Python 手写二分,谓词 nums[m] >= target 缩右区间,nums[m] < target 缩左区间。
关键理解:lower_bound 返回的位置既是"已存在元素的索引"(若该元素等于 target),也是"应插入的位置"(若不存在)。二者统一在同一次二分中。
代码
cpp
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int searchInsert(vector<int> &nums, int target) {
return lower_bound(nums.begin(), nums.end(), target) - nums.begin();
}
};
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n, t;
cin >> n >> t;
vector<int> a(n);
for (int &x : a)
cin >> x;
cout << Solution().searchInsert(a, t) << '\n';
return 0;
}python
#!/usr/bin/env python3
from typing import List
class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
lo, hi = 0, len(nums)
while lo < hi:
m = (lo + hi) // 2
if nums[m] >= target:
hi = m
else:
lo = m + 1
return lo
def main():
n, t = map(int, input().split())
a = list(map(int, input().split()))
print(Solution().searchInsert(a, t))
if __name__ == "__main__":
main()复杂度
- 时间复杂度:
。 - 空间复杂度:
。
总结
lower_bound 是二分查找的基础操作:找第一个满足谓词的位置。本题谓词是