C. Dominated Subarray
Let's call an array 𝑡 dominated by value 𝑣 in the next situation.
At first, array 𝑡 should have at least 2 elements. Now, let's calculate number of occurrences of each number 𝑛𝑢𝑚 in 𝑡 and define it as 𝑜𝑐𝑐(𝑛𝑢𝑚). Then 𝑡 is dominated (by 𝑣) if (and only if) 𝑜𝑐𝑐(𝑣)>𝑜𝑐𝑐(𝑣′) for any other number 𝑣′. 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 𝑎1,𝑎2,…,𝑎𝑛. Calculate its shortest dominated subarray or say that there are no such subarrays.
The subarray of 𝑎 is a contiguous part of the array 𝑎, i. e. the array 𝑎𝑖,𝑎𝑖+1,…,𝑎𝑗 for some 1≤𝑖≤𝑗≤𝑛.
Input
The first line contains single integer 𝑇 (1≤𝑇≤1000) — the number of test cases. Each test case consists of two lines.
The first line contains single integer 𝑛 (1≤𝑛≤2⋅105) — the length of the array 𝑎.
The second line contains 𝑛 integers 𝑎1,𝑎2,…,𝑎𝑛 (1≤𝑎𝑖≤𝑛) — the corresponding values of the array 𝑎.
It's guaranteed that the total length of all arrays in one test doesn't exceed 2⋅105.
Output
Print 𝑇 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.
Example
input
4
1
6
1 2 3 4 5 1
9
4 1 2 4 5 4 3 2 1
3 3 3 3
output
-1
3
2
Note
In the first test case, there are no subarrays of length at least 2, so the answer is −1.
In the second test case, the whole array is dominated (by 1) and it's the only dominated subarray.
In the third test case, the subarray 𝑎4,𝑎5,𝑎6 is the shortest dominated subarray.
In the fourth test case, all subarrays of length more than one are dominated.
題意
現在定義一個Dominated number,表示這個序列中這個數字出現最多。
現在給n個數,你需要找到一個最短的區間,使得這個區間裡面存在唯一一個出現次數最多的數。
題解
其實思考思考,我們會發現出現最多的就是出現兩個而已。
那麼我們就暴力枚舉每一個數,看上一個數在哪個位置即可,然後選擇最短的就行。
代碼
#include<bits/stdc++.h>
using namespace std;
const int maxn = 200005;
int n,a[maxn],c[maxn];
void solve(){
cin>>n;
int mx = 9999999;
for(int i=1;i<=n;i++){
c[i]=0;
}
for(int i=1;i<=n;i++){
cin>>a[i];
if(c[a[i]]!=0){
mx=min(i-c[a[i]]+1,mx);
}
c[a[i]]=i;
}
if(mx==9999999){
cout<<"-1"<<endl;
}else{
cout<<mx<<endl;
}
}
int main(){
int t;cin>>t;
while(t--)solve();
}