35. Search Insert Position

题目链接: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

这道题的要求是在一个有序数组中,,找到给定的target在数组中出现的位置。如果不存在,返回插入target元素后仍使数组有序的插入位置。可以假设数组中没有重复元素。

和Search for a Range类似,同样采用二分搜索。在target等于A[m]的时候,可以采取和target小于A[m]情况同样的操作,即r=m-1,这样可以确保最后l就是target出现的位置或是target插入的位置。

时间复杂度:O(logn)

空间复杂度:O(1)

以诚感人者,人亦诚而应。

35. Search Insert Position

相关文章:

你感兴趣的文章:

标签云: