给定一个已经升序排好序的数组,以及一个数target,如果target在数组中,返回它在数组中的位置。
否则,返回target插入数组后它应该在的位置。
假设数组中没有重复的数。以下是简单的示例:
[1,3,5,6], 5 → 2
[1,3,5,6], 2 → 1
[1,3,5,6], 7 → 4
[1,3,5,6], 0 → 0
提示:输入一个整数n,以及其对应的数组A[n],最后输入target
searchInsert(int A[], int n, int target)
样例1
输入:
3
1 3 5
2
输出:
1
#include <stdio.h>
#include <malloc.h>
int searchInsert(int A[], int n, int target){
int low = 0;
int high = n - 1;
int index; //未查找到时显示应该插入的索引
//使用二分查找target在不在A中
while(low <= high)
{
int mid = (low + high)/2;
if(A[mid] == target)
{
return mid;
}else if(A[mid] < target)
{
low = mid + 1;
index = low;
}else{
high = mid - 1;
index = high + 1;
}
}
return index;
}
int main(int argc, char **argv) {
int i,n,result,target;
scanf("%d",&n);
int *a = (int *)malloc(n * sizeof(int));
for(i=0;i<n;i++){
scanf("%d",&a[i]);
}
scanf("%d",&target);
result = searchInsert(a,n,target);
printf("%d",result);
return 0;
}