【LeetCode】35. Search Insert Position (2 solutions)

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

 

解法一:线性查找(linear search)

class Solution 
{
public:
    int searchInsert(int A[], int n, int target) 
    {
        if(n>0 && target <= A[0])
            return 0;
        for(int i = 0; i < n; i ++)
        {
            if(A[i] >= target)
                return i;
        }
        return n;
    }
};

 

解法二:二分查找(binary search)

class Solution {
public:
    int searchInsert(int A[], int n, int target) {
        int low = 0;
        int high = n-1;
        while(low <= high)
        {
            int mid = low + (high-low) / 2;
            if(A[mid] == target)
                return mid;
            else if(A[mid] > target)
                high = mid - 1;
            else
                low = mid + 1;
        }
        return low;
    }
};

posted @ 2014-07-09 21:21  陆草纯  阅读(291)  评论(1编辑  收藏  举报