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

 1 class Solution
 2 {
 3 public:
 4     int searchInsert(int A[], int n, int target)
 5     {
 6         int l = 0, r = n - 1, m;
 7         while(l <= r)
 8         {
 9             m = (l + r) / 2;
10             if(target <= A[m])
11                 r = m - 1;
12             else
13                 l = m + 1;
14         }
15         return l;
16     }
17 };