leetcode-Search Insert Position

来源:互联网 发布:编程判断质数 编辑:程序博客网 时间:2024/06/13 00:53

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


思路:二分法(寻找第一个比target大或相等的元素)

代码:

int searchInsert(int A[], int n, int target) {
        int p=0;
int q=n-1;
int mid=0;
while(p<=q)
{
mid=(p+q)/2;
if(target <= A[mid])
{
if(mid>0 && target>A[mid-1])
{
return mid;
}
else if(mid == 0)
{
return mid;
}
else
{
q=mid-1;
}
}
else
{
if(mid+1<n && target<=A[mid+1])
{
return mid+1;
}
else if(mid+1 == n)
{
return mid+1;
}
else
{
p=mid+1;
}
}
    }
    }

0 0
原创粉丝点击