-
Notifications
You must be signed in to change notification settings - Fork 0
/
697.hpp
54 lines (47 loc) · 1.14 KB
/
697.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#ifndef LEETCODE_697_HPP
#define LEETCODE_697_HPP
#include <iostream>
#include <queue>
#include <algorithm>
#include <vector>
#include <unordered_map>
#include <unordered_set>
#include <set>
#include <numeric>
#include <stack>
#include <string>
using namespace std;
class CntPos {
public:
int cnt;
int left;
int right;
void update(int pos) {
if (this->cnt == 0) {
this->left = pos;
}
this->right = pos;
cnt++;
}
};
class Solution {
public:
int findShortestSubArray(vector<int> &nums) {
unordered_map<int, CntPos> cnts;
for (int i = 0; i < nums.size(); ++i) {
cnts[nums[i]].update(i);
}
int mcnt = 1, mlen = 1;
for (auto &p : cnts) {
if (p.second.cnt > mcnt) {
mcnt = p.second.cnt;
mlen = p.second.right - p.second.left + 1;
} else if (p.second.cnt == mcnt && p.second.right - p.second.left + 1 < mlen) {
mcnt = p.second.cnt;
mlen = p.second.right - p.second.left + 1;
}
}
return mlen;
}
};
#endif //LEETCODE_697_HPP