题目传送门
简单的贪心。如果一个子数组被支配了,那么就是只有一个唯一的众数,现在需要求出这个子数组的最短长度,那么所有可能的情况就应该是有 个数字在这个子数组中出现了 次,这个子数组中其它的数字都只出现 次。所以我们用 map 记录一个数字 上一次出现的下标为 ,等这个数字 再一次出现在下标 时就用 更新答案。最终如果无解输出 即可。
#include<bits/stdc++.h>
#define int long long
using namespace std;
unordered_map<int, int> last;
int T, n, x;
signed main() {
ios::sync_with_stdio(0);
cin.tie(0), cout.tie(0);
cin >> T;
while (T--) {
cin >> n;
last.clear();
int ans = INT_MAX;
for (int i = 1; i <= n; i++) {
cin >> x;
if (last[x]) ans = min(ans, i - last[x] + 1);
last[x] = i;
}
if (ans == INT_MAX) cout << -1 << '\n';
else cout << ans << '\n';
}
return 0;
}