给定一个已经升序排好序的数组,以及一个数 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。
第二行输入 n 个整数,表示数组A[n]
。
第三行输入 target。
输出格式
输出一行,为要求返回的结果。
样例输入
3 1 3 5 2
样例输出
1
C++:
#include<iostream>
#include<string>using namespace std;
int main()
{
int n,tar;
int count=0;
cin>>n;
int A[n];
for(int j=0;j<n;j++)
{
cin>>A[j];
}
cin >>tar;
for(int i=0;i<n;i++)
{
if(A[i]>=tar)
{
count=i;
break;
}
}
if(tar>A[n-1])
count=n;
cout<<count<<endl;
}