problem
题意:首先是原数组的度,其次是和原数组具有相同的度的最短子数组。那么最短子数组就相当于子数组的首末数字都是统计度的数字。
solution1:
class Solution { public: int findShortestSubArray(vector<int>& nums) { int n = nums.size(), res = INT_MAX, degree = 0; unordered_map<int, int> m; unordered_map<int, pair<int, int>> pos; for(int i=0; i<n; ++i) { m[nums[i]]++; if(m[nums[i]]==1) pos[nums[i]] = {i, i}; else pos[nums[i]].second = i; degree = max(degree, m[nums[i]]); } for(auto a:m) { if(degree == a.second) { res = min(res, pos[a.first].second-pos[a.first].first+1); } } return res; } };
solution2:
参考
1. Leetcode_easy_697. Degree of an Array;
2. Grandyang;
完