697. Degree of an Array

problem

solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public:
int findShortestSubArray(vector<int>& nums) {
unordered_map<int,vector<int>> mp;
int n = nums.size();
for(int i=0;i<n;++i){
mp[nums[i]].push_back(i);
}

int degree = 0;
for(auto it=mp.begin();it!=mp.end();it++) degree=max(degree,int(it->second.size()));
int shortest=nums.size();
for(auto it=mp.begin();it!=mp.end();it++)
{
if(it->second.size()==degree)
{
shortest=min(shortest,it->second.back()-it->second[0]+1);
}
}
return shortest;
}
};

analysis

  • time complexity O(n)
  • space complexity O(n)