Training 2 - C题
You are given an array of n integer numbers a0, a1, …, an - 1. Find the distance between two closest (nearest) minimums in it. It is guaranteed that in the array a minimum occurs at least two times.
Input
The first line contains positive integer n (2 ≤ n ≤ 105) — size of the given array. The second line contains n integers a0, a1, …, an - 1 (1 ≤ ai ≤ 109) — elements of the array. It is guaranteed that in the array a minimum occurs at least two times.
Output
Print the only number — distance between two nearest minimums in the array.
Examples
Input
2
3 3
Output
1
Input
3
5 6 5
Output
2
Input
9
2 1 3 5 4 1 2 3 1
Output
3
#pragma warning (disable:4996)
#include <iostream>
#include <algorithm>
#include <iomanip>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <vector>
#include <queue>
#define inf 0X7f7f7f7f
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const int maxn = 1e5 + 5;
struct Node
{
int val;
int pos;
friend bool operator<(Node a, Node b)
{
if (a.val == b.val)
return a.pos > b.pos;
return a.val > b.val;
}
};
priority_queue<Node> a;
int main()
{
int n;
scanf("%d", &n);
int num = 0;
int ans = inf;
for (int i = 0; i < n; i++)
{
int val;
scanf("%d", &val);
Node t;
t.val = val;
t.pos = i;
a.push(t);
}
num = a.top().val;
int lastpos = a.top().pos;
a.pop();
while (a.size() != 0 && a.top().val == num)
{
ans = min(ans, a.top().pos - lastpos);
lastpos = a.top().pos;
a.pop();
}
printf("%d\n", ans);
return 0;
}
思路:
用优先队列存储,将最小值取出计算当前的距离并更新答案。