给定一个已经升序排好序的数组,以及一个数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)
样例输入
3 1 3 5 2
样例输出
1
#include <stdio.h>
int searchInsert(int A[], int n, int target);
int main()
{
int n,A[10000],target,i;
scanf("%d",&n);
for(i = 0;i < n;i++)
{
scanf("%d",&A[i]);
}
scanf("%d",&target);
i = searchInsert(A,n,target);
printf("%d\n",i);
return 0;
}
int searchInsert(int A[], int n, int target)
{
int i = 0;
for(i = 0;i < n;i++)
{
if(A[i] == target)
return i+1;
else if(A[i] > target)
return i;
}
if(i == n)
return n;
}
原文地址:http://blog.csdn.net/cnshsh/article/details/39397537