-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathDegreeOfAnArray.cpp
More file actions
58 lines (50 loc) · 1.43 KB
/
Copy pathDegreeOfAnArray.cpp
File metadata and controls
58 lines (50 loc) · 1.43 KB
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
55
56
57
58
class Solution {
public:
void insertInMap(map<int, int>& m1, int num){
if(m1.find(num) == m1.end()){
m1[num] = 1;
}
else{
m1[num]++;
}
}
void changeAns(int& ans, int num){
if(ans == -1){
ans = num;
}
else{
ans = min(ans, num);
}
}
void deleteFromMap(map<int, int>& m1, int num){
m1[num]--;
}
int findShortestSubArray(vector<int>& nums) {
int n = nums.size(), degree = 0, ans = -1, j = 0;
map<int, int> m1, m2;
for(int i = 0; i < n; i++){
insertInMap(m1, nums[i]);
degree = max(degree, m1[nums[i]]);
}
for(int i = 0; i < n; i++){
insertInMap(m2, nums[i]);
if(m2[nums[i]] >= degree){
if(m2[nums[i]] == degree){
while(nums[j] != nums[i]){
deleteFromMap(m2, nums[j]);
j++;
}
}
else if(m2[nums[i]] > degree){
while(nums[j] != nums[i]){
deleteFromMap(m2, nums[j]);
j++;
}
deleteFromMap(m2, nums[j]);
}
changeAns(ans, i-j+1);
}
}
return ans;
}
};