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.

Example
inputCopy

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
outputCopy
-1
6
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 a4,a5,a6 is the shortest dominated subarray.

In the fourth test case, all subarrays of length more than one are dominated.

题意:
序列t至少有2个元素,我们称序列t被数字出现次数最多的元素v主导,且出现次数最多的元素必须是唯一的
你被给予了序列a1, a2, …, an,计算它的最短受主导子序列,或者说这里没有这种序列

也就是说给你n个数,你需要找一个最短的区间,使得这个区间存在唯一一个出现次数最多的数

解析:
其实区间出现最多的就是出现两个。因为你不管出现多少个,要算这个区间的长度的时候,看的就是相同2个之间的距离
所以暴力枚举我们只要和上一个位置相比较,取最小的


#include<bits/stdc++.h>
using namespace std;
const int N=2e5+10000;
int a[N],n,x;
struct node
{
	int d;
	int pos;
	int num;
}v[N];
map<int,int> mp;
bool cmp(const node &a,const node &b)
{
	return a.num>b.num;
}
int main()
{
	int t;
	scanf("%d",&t);
	while(t--)
	{
		scanf("%d",&n);
		mp.clear();
		for(int i=1;i<=n;i++) scanf("%d",&a[i]);
		int ans=0x3f3f3f3f; 
		for(int i=1;i<=n;i++)
		{
			if(mp[a[i]])
			{
				ans=min(ans,i-mp[a[i]]+1);
			}
			mp[a[i]]=i;
		}
		if(ans==0x3f3f3f3f) puts("-1");
		else printf("%d\n",ans);
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值