首页 > 其他 > 详细

LeetCode:Search Insert Position

时间:2015-12-12 13:55:16      阅读:164      评论:0      收藏: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

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

假设小于,则返回medium。


代码:

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;
    }

LeetCode:Search Insert Position

原文:http://www.cnblogs.com/mengfanrong/p/5041107.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!