这个题要求元素插入到数组中的位置,对于判断函数,刚开始写的很复杂,后来好了。
给定一个已经升序排好序的数组,以及一个数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){
for (int i = 0; i < n; i++)
if (A[i] >= target)
return i;
return n;
}
int main()
{
int n,i,t;
scanf("%d",&n);
int a[n];
for(i=0;i<n;i++)
scanf("%d",&a[i]);
scanf("%d",&t);
printf("%d\n",searchInsert(a, n, t));
return 0;
}