码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode:Search Insert Position

时间:2014-10-28 12:19:51      阅读:191      评论:0      收藏:0      [点我收藏+]

标签:algorithm   leetcode   

问题描述:

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

LeetCode:Search Insert Position

标签:algorithm   leetcode   

原文地址:http://blog.csdn.net/yao_wust/article/details/40537091

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!