【leetcode】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

 
 
 
 
采用[0,n-1]左闭右闭的方式查找
考虑几种情况
 
[1,2]查找0
 
第一步:left=0,right=1,A[mid]=1>0  ===> right=1-1=0
第二步:left=0,right=0,A[mid]=1>0 ===> right=0-1=-1
停止,返回left即可
 
[1,2]查找3
第一步:left=0,right=1,A[mid]=1<3 ===>left=0+1=1
第二部:left=1,right=1,A[mid]=2<3 ===>left=1+1=2
停止,返回left即可
 
[1,2]查找1.5
第一步:left=0,right=1,A[mid]=1<1.5 ===>left=0+1=1
第二步:left=1,right=1,A[mid]=2>1.5 ===>right=1-1=0
停止,返回left即可
 
综上,如果查找不到,只需要返回left即可
 
 
 
采用二分查找,关于二分查找
 
 1 class Solution {
 2 public:
 3     int searchInsert(int A[], int n, int target) {
 4        
 5         int left=0;
 6         int right=n-1;
 7         int mid;
 8         while(left<=right)
 9         {
10             mid=(left+right)/2;
11            
12             if(A[mid]<target)
13             {
14                 left=mid+1;
15             }
16             else if(A[mid]>target)
17             {
18                 right=mid-1;
19             }
20             else
21             {
22                 return mid;
23             }
24         }
25  
26         return left;
27     }
28 };
原文地址:https://www.cnblogs.com/reachteam/p/4251656.html