C. Dominated Subarray
Let’s call an array t dominated by value v in the next situation.
At first, array t should have at least 2 elements. Now, let’s calculate number of occurrences of each number num in t and define it as occ(num). Then t is dominated (by v) if (and only if) occ(v)>occ(v′) for any other number v′. For example, arrays [1,2,3,4,5,2], [11,11] and [3,2,3,2,3] are dominated (by 2, 11 and 3 respectevitely) but arrays [3], [1,2] and [3,3,2,2,1] are not.
Small remark: since any array can be dominated only by one number, we can not specify this number and just say that array is either dominated or not.
You are given array a1,a2,…,an. Calculate its shortest dominated subarray or say that there are no such subarrays.
The subarray of a is a contiguous part of the array a, i. e. the array ai,ai+1,…,aj for some 1≤i≤j≤n.
Input
The first line contains single integer T (1≤T≤1000) — the number of test cases. Each test case consists of two lines.
The first line contains single integer n (1≤n≤2⋅105) — the length of the array a.
The second line contains n integers a1,a2,…,an (1≤ai≤n) — the corresponding values of the array a.
It’s guaranteed that the total length of all arrays in one test doesn’t exceed 2⋅105.
Output
Print T integers — one per test case. For each test case print the only integer — the length of the shortest dominated subarray, or −1 if there are no such subarrays.
一道思维题,我们只要记录每个数字出现的次数,然后当一个数字出现两次后,用当前位置减去它上一次出现的位置,取最小值就行;
代码:
#include<bits/stdc++.h>
#define LL long long
#define pa pair<int,int>
#define lson k<<1
#define rson k<<1|1
#define inf 0x3f3f3f3f
//ios::sync_with_stdio(false);
using namespace std;
const int N=1100;
const int M=200100;
const LL mod=1e9+7;
int a[200100];
int v[200100];
int last[200100];
int main(){
ios::sync_with_stdio(false);
int t;
cin>>t;
while(t--){
int n;
cin>>n;
for(int i=1;i<=n;i++){
cin>>a[i];
}
memset(v,0,sizeof(v));
if(n==1){
cout<<-1<<endl;
continue;
}
int mmin=2e9;
for(int i=1;i<=n;i++){
v[a[i]]++;
if(v[a[i]]==1){
last[a[i]]=i;
}
if(v[a[i]]>1){
mmin=min(mmin,i-last[a[i]]+1);
last[a[i]]=i;
}
}
if(mmin!=2e9)
cout<<mmin<<endl;
else cout<<-1<<endl;
}
return 0;
}
总结,可能是英文题目的原因,导致看题总是看不太懂;研究题目就要半天,思维还是太慢了;