LeetCode: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

解题思路:二分查找。假设没有找到,比較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;
    }

原文地址:https://www.cnblogs.com/mengfanrong/p/5041107.html