【CodeForces 1257C --- Dominated Subarray】

徘徊边缘 提交于 2019-12-03 06:06:42

【CodeForces 1257C --- Dominated Subarray】


Description

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.

Sample Input

4
1
1
6
1 2 3 4 5 1
9
4 1 2 4 5 4 3 2 1
4
3 3 3 3

Sample Output

-1
6
3
2

AC代码:

#include <iostream>
#include <algorithm>
#include <cmath>
#include <map>
using namespace std;
#define SIS std::ios::sync_with_stdio(false),cin.tie(0),cout.tie(0)
const int MAXN = 2e5+5;
int arr[MAXN];

int main()
{
    SIS;
    int T;
    cin >> T;
    while(T--)
    {
        map<int,int> m;
        int n,ans=0,cnt=0x3f3f3f3f;
        cin >> n;
        for(int i=1;i<=n;i++)
        {
            cin >> arr[i];
            if(i>1 && m[arr[i]]!=0 && cnt>i-m[arr[i]])
            {
                cnt=i-m[arr[i]];
            }
            m[arr[i]]=i;
        } 
        if(n<2 || cnt<1 || cnt==0x3f3f3f3f)
            cout << -1 << endl;
        else
            cout << cnt+1 << endl;
    }
    return 0;
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!