一,思路:
1.根据题目的规则,我们可以知道一个漂亮数组的首尾是要相同的,因为这两个元素是无法改变的只能通过删除操做,所以我们可以根据首尾元素是什么来判断,如果该数组要全部相同,那么那个相同的元素一定是首尾元素。
2.还有一种情况就是当有两个不同于首尾的元素紧挨在一起,这样也是无法变成漂亮数组的。如:1 2 2 1 2 1------>这种情况那两个挨在一起的 2 是无法变成 1的。
3.所以现在我们要是一个漂亮数组不在漂亮, 就可以从上面两点出发,将首尾元素变得不同,或者是像 上面的 2,一样让他们挨在一起。
二,代码:
#include <iostream>
#include <algorithm>
#include <cmath>
#include <cstring>
using namespace std;
const int N = 3e5 + 10, M = 1e9 + 7;
typedef long long ll;
typedef pair<int, int> pii;
int arr[N];
void Solved()
{
int n;
cin>>n;
for(int i=1;i<=n;i++) cin>>arr[i];
//last记录上一次,不同于arr[1]的元素下标
int last=0,ans=1e9;
for(int i=1;i<=n;i++){
if(arr[i]!=arr[1]){
ans=min(ans,i-last-1);
last=i;
}
}
//还有后面一段,也要进行比较----> 1 1 2 1 1 2 1 ,肯定删最后一个元素是最优的
ans=min(ans,n-last);
//元素全部相同的情况
if(last==0) cout<<-1<<endl;
else{
cout<<ans<<endl;
}
}
int main()
{
int t;
cin >> t;
//t=1;
while (t--)
{
Solved();
}
return 0;
}