D. Extra Element
time limit per test2 seconds
memory limit per test256 megabytes
inputstandard input
outputstandard output
A sequence a1,a2,…,ak is called an arithmetic progression if for each i from 1 to k elements satisfy the condition ai=a1+c⋅(i−1) for some fixed c.
For example, these five sequences are arithmetic progressions: [5,7,9,11], [101], [101,100,99], [13,97] and [5,5,5,5,5]. And these four sequences aren’t arithmetic progressions: [3,1,2], [1,2,4,8], [1,−1,1,−1] and [1,2,3,3,3].
You are given a sequence of integers b1,b2,…,bn. Find any index j (1≤j≤n), such that if you delete bj from the sequence, you can reorder the remaining n−1 elements, so that you will get an arithmetic progression. If there is no such index, output the number -1.
Input
The first line of the input contains one integer n (2≤n≤2⋅105) — length of the sequence b. The second line contains n integers b1,b2,…,bn (−109≤bi≤109) — elements of the sequence b.
Output
Print such index j (1≤j≤n), so that if you delete the j-th element from the sequence, you can reorder the remaining elements, so that you will get an arithmetic progression. If there are multiple solutions, you are allowed to print any of them. If there is no such index, print -1.
Examples
inputCopy
5
2 6 8 7 4
outputCopy
4
inputCopy
8
1 2 3 4 5 6 7 8
outputCopy
1
inputCopy
4
1 2 4 8
outputCopy
-1
Note
Note to the first example. If you delete the 4-th element, you can get the arithmetic progression [2,4,6,8].
Note to the second example. The original sequence is already arithmetic progression, so you can delete 1-st or last element and you will get an arithmetical progression again.
思路:
给定n个数字判断是否能在删除掉一个数字后形成等差数列
对值排序后对前三个数字进行预处理,
从第四个数值开始对等差满足次数和删除的下标及时记录更新即可
struct node {
int x,e;
} a[200010];
bool cmp(node a,node b) {
return a.e<b.e;
}
int main() {
int n=read();
for(int i=1; i<=n; i++) {
cin>>a[i].e;
a[i].x=i;
}
if(n<=3) {
cout<<1<<endl;
return 0;
}
sort(a+1,a+1+n,cmp);
int d1=a[2].e-a[1].e;
int d2=a[3].e-a[2].e;
int d3=a[4].e-a[3].e;
int ans=0;
int dif=d1;
int cnt=0;
int i=4;
if(d1!=d2&&d2==d3) {
ans=a[1].x;
dif=d2;
++cnt;
} else if(d1+d2==d3&&d1!=d3) {
ans=a[2].x;
dif=d3;
++cnt;
} else if(d2+d3==d1&&d2!=d1) {
ans=a[3].x;
dif=d1;
++cnt;
i=5;
} else if(d1==d2&&d2==d3) {
ans=a[1].x;
dif=d1;
} else if(d1!=d2&&d2!=d3&&d1+d2!=d3) {
ans=-1;
}
if(ans!=-1) {
for(; i<=n; ++i) {
if(a[i].e-a[i-1].e!=dif) {
ans=a[i].x;
if(a[i+1].e-a[i-1].e==dif||i==n) {
++i;
} else {
ans=-1;
break;
}
++cnt;
//cout<<cnt<<endl;
}
if(cnt>1) {
ans=-1;
break;
}
}
}
cout<<ans<<endl;
return 0;
}