LeetCode:Search Insert Position

时间:2014-10-28 12:19:51   收藏:0   阅读:191

问题描述:

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

解题思路:二分查找。如果没有找到,比较A[medium]与target的大小。如果A[medium]大于target,则返回medium+1。如果小于,则返回mediu。


代码:

int head = 0;
    int tail = n-1;
    int medium;
    while(head <= tail)
    {
        medium = (head + tail) / 2;
        if(A[medium] == target)
            return medium;
        /*if(tail - head == 1 && A[tail] != target && A[head] != target)
        {
            if(target > A[tail])
                return tail + 1;
            else if(target > A[head] && target < A[tail])
                return tail;
            else
                return head;
        }*/
        if(A[medium] > target)
            tail = medium - 1;
        if(A[medium] < target)
            head = medium + 1;
    }
    if(head == tail)
    {
        if(target > A[tail])
            return tail+1;
        else
            return head;
    }

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!