索引:[LeetCode] Leetcode 题解索引 (C++/Java/Python/Sql)
Github: https://github.com/illuz/leetcode
035. Search Insert Position (Medium)
链接:
题目:https://leetcode.com/problems/search-insert-position/
代码(github):https://github.com/illuz/leetcode
题意:
要把一个数有序插入到一个有序数组里,问插入的位置。
分析:
还是二分变形题。
- 用 STL 的
lower_bound
偷懒。 - 二分,最后注意判断一下是否找到,要输出什么。
代码:
C++:
class Solution {
public:
int searchInsert(int A[], int n, int target) {
// if use lower_bound
// return lower_bound(A, A + n, target) - A;
int l = 0, r = n - 1, mid = 0;
while (l < r) {
mid = l + (r - l) / 2;
// mid = (l + r) / 2;
if (A[mid] < target)
l = mid + 1;
else
r = mid;
}
return A[l] < target ? l + 1 : l;
}
};