File tree Expand file tree Collapse file tree 1 file changed +29
-0
lines changed Expand file tree Collapse file tree 1 file changed +29
-0
lines changed Original file line number Diff line number Diff line change
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
+ };
You can’t perform that action at this time.
0 commit comments