這個題要求元素插入到數組中的位置,對於判斷函數,剛開始寫的很複雜,後來好了。
給定一個已經升序排好序的數組,以及一個數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;
}