-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathdegree-of-an-array.cpp
40 lines (27 loc) · 1.01 KB
/
degree-of-an-array.cpp
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
class Solution {
struct NumRange {
int count;
int start;
int end;
// NumRange(int n,int s, int e): count(n), start(s), end(e) {}
};
public:
int findShortestSubArray(vector<int>& nums) {
unordered_map<int, NumRange> map;
int maxcnt = 1, mindis = 1;
for (int i = 0; i < nums.size(); ++i) {
int curr = nums[i];
if (!map.count(curr))
map[curr] = { 1, i, i };
else {
map[curr].end = i;
if (++map[curr].count > maxcnt) {
maxcnt = map[curr].count;
mindis = map[curr].end - map[curr].start + 1;
} else if (map[curr].count == maxcnt)
mindis = min(mindis, map[curr].end - map[curr].start + 1);
}
}
return mindis;
}
};