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
题意:在已排序的数组中查找给定数字,若有,返回下标,没有,则返回插入位置
思路:题意的要求应该理解成,应该返回的是第一个不小于目标值的下标。所以用二分查找即可。详情可见我之前的博客关于二分查找的总结。代码如下:
1 class Solution { 2 public: 3 int searchInsert(int A[], int n, int target) 4 { 5 int lo=0,hi=n; 6 while(lo<hi) 7 { 8 int mid=lo+((hi-lo)>>1); 9 if(A[mid]<target) 10 lo=mid+1; 11 else 12 hi=mid; 13 } 14 return hi; 15 } 16 };
时间: 2024-10-14 02:48:20