Skip to content

Commit 1e8a763

Browse files
authored
Create degree-of-an-array.cpp
1 parent 0a59c20 commit 1e8a763

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

C++/degree-of-an-array.cpp

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
// Time: O(n)
2+
// Space: O(n)
3+
4+
class Solution {
5+
public:
6+
int findShortestSubArray(vector<int>& nums) {
7+
unordered_map<int, int> left, right;
8+
unordered_map<int, int> counts;
9+
for (int i = 0; i < nums.size(); ++i) {
10+
if (left.count(nums[i]) == 0) {
11+
left[nums[i]] = i;
12+
}
13+
right[nums[i]] = i;
14+
++counts[nums[i]];
15+
}
16+
auto degree = max_element(counts.begin(), counts.end(),
17+
[](const pair<int, int>& a,
18+
const pair<int, int>& b) {
19+
return a.second < b.second;
20+
})->second;
21+
auto result = numeric_limits<int>::max();
22+
for (const auto& kvp : counts) {
23+
if (kvp.second == degree) {
24+
result = min(result, right[kvp.first] - left[kvp.first] + 1);
25+
}
26+
}
27+
return result;
28+
}
29+
};

0 commit comments

Comments
 (0)