1. 程式人生 > >[Leetcode] search insert position 尋找插入位置

[Leetcode] search insert position 尋找插入位置

dex http 應該 nbsp arr 位置 love ray array

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 };

[Leetcode] search insert position 尋找插入位置