跳到主要内容

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

分析

std::lower_bound()

代码

// Search Insert Position
// 重新实现 lower_bound
// 时间复杂度O(logn),空间复杂度O(1)
public class Solution {
public int searchInsert(int[] nums, int target) {
return lower_bound(nums, 0, nums.length, target);
}

int lower_bound (int[] A, int first, int last, int target) {
while (first != last) {
int mid = first + (last - first) / 2;
if (target > A[mid]) first = ++mid;
else last = mid;
}

return first;
}
}

相关题目