LeetCode Search Insert Position

class Solution {
public:
    int searchInsert(int A[], int n, int target) {
        if (A == NULL || n < 1) return 0;
        int p = -1, q = n;
        while (p + 1 < q) {
            int mi = (p + q) / 2;
            if (A[mi] > target) {
                q = mi;
            } else if (A[mi] < target) {
                p = mi;
            } else {
                return mi;
            }
        }
        return q;
    }
};

水一发,第一道一两分钟搞定的题,好像已经会背了

第二轮:

按照题意实际就是实现一个lower_bound函数

class Solution {
    /** 
     * param A : an integer sorted array
     * param target :  an integer to be inserted
     * return : an integer
     */
public:
    int searchInsert(vector<int> &A, int target) {
        // write your code here
        
        int lo = 0;
        int hi = A.size();
        
        while (lo < hi) {
            int mid = (lo + hi) / 2;
            if (A[mid] < target) {
                lo = mid + 1;
            } else {
                hi = mid;
            }
        }
        
        return lo;
    }
};

 

posted @ 2014-06-20 16:19  卖程序的小歪  阅读(157)  评论(0编辑  收藏  举报