【LeetCode】Search Insert Position

description:

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

code : 两种方法1A 

class Solution {
public:
    int searchInsert(int A[], int n, int target) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        
        // STL method.
        //int *pos = lower_bound(A,A+n,target);
        //if(pos == A+n)
        //{
        //    return n;
        //}
        //else return pos - A;
        
        // binary search method.
        int lhs = 0, rhs = n-1;
        while(lhs <= rhs)
        {
            int mid = (lhs + rhs)>>1;
            if(A[mid] == target) return mid;
            else if(A[mid] < target) lhs = mid + 1;
            else rhs = mid - 1;
        }
        
        return lhs;
    }
};


你可能感兴趣的:(LeetCode)