Search Insert Position 分类: Leetcode 2014-12-06 16:18 78人阅读 评论(0) 收藏

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

最初的想法是从头到尾遍历这个数组,这样也是可以做的

class Solution {
public:
    int searchInsert(int A[], int n, int target) {
        if(target<=A[0]) return 0;
        if(target==A[n-1]) return n-1;
        if(target>A[n-1]) return n;
        int begin=0,last=n-1;
        while(A[begin]<target)
        {
                begin++;
        }
        return begin;
    }
};
不过用二分法在某些情况的确可以提高查找效率

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


版权声明:本文为博主原创文章,未经博主允许不得转载。

原文地址:https://www.cnblogs.com/learnordie/p/4656985.html