首页 > 代码库 > LeetCode:Search Insert Position

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。如果小于,则返回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