索引:[LeetCode] Leetcode 题解索引 (C++/Java/Python/Sql)
Github:
https://github.com/illuz/leetcode
题目:https://leetcode.com/problems/search-insert-position/
代码(github):https://github.com/illuz/leetcode
要把一个数有序插入到一个有序数组里,问插入的位置。
还是二分变形题。
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;
}
};
[LeetCode] 035. Search Insert Position (Medium) (C++)
原文:http://blog.csdn.net/hcbbt/article/details/44244775