[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

分析:

        二分查找。其实就是实现lower_bound()的功能。不过在有些时候,lower_bound()处理的对象有局限性,不方便的时候,例如:[LeetCode]—Search a 2D Matrix 有序二维矩阵中查找目标值,用该代码能够有很好的替代作用。

class Solution {
public:
    int searchInsert(int A[], int n, int target) {
        int high=n;
        int low=0;

    while(low<high){
        int mid=(high+low)/2;
        if(A[mid]>=target){
            high=mid;
        }else
            low=mid+1;
        }
     return high;

    }
};

你可能感兴趣的:([LeetCode]—Search Insert Position 有序数组中找目标插入的位置)