Given a non-empty array of non-negative integers nums
, the degree of this array is defined as the maximum frequency of any one of its elements.
Your task is to find the smallest possible length of a (contiguous) subarray of nums
, that has the same degree as nums
.
Example 1:
Input: [1, 2, 2, 3, 1] Output: 2 Explanation: The input array has a degree of 2 because both elements 1 and 2 appear twice. Of the subarrays that have the same degree: [1, 2, 2, 3, 1], [1, 2, 2, 3], [2, 2, 3, 1], [1, 2, 2], [2, 2, 3], [2, 2] The shortest length is 2. So return 2.
Example 2:
Input: [1,2,2,3,1,4,2] Output: 6
Note:
nums.length
will be between 1 and 50,000.nums[i]
will be an integer between 0 and 49,999.
题目要求给定一个非空非负的整数数组,先求出数组的度,也就是出现次数最多的那个数字的出现次数。
然后找出这个数组的最小连续子数组并返回子数组的长度,要求这个子数组的度和原数组的度相同。
这是个很容易的题。就写了一个思路简单但是不够简洁的方法。
思路:首先利用map(m)求出给定数组的度,这里需要注意的是有可能含有相同度的多个数字。所以用一个数组vec来存储数组的度相同的数字。然后利用另一个map(n)来存储数组中从尾到头不同数字的索引(遍历数组,用 map映射数值到索引,重复的数字就会被覆盖并更新索引),这个索引也就是子数组的右边界。最后利用两层for循环,找出子数组的左边界。并返回最小的子数组长度即可。
想法比较片段化,后续想出更简单的方法再更新。
class Solution { public: int findShortestSubArray(vector<int>& nums) { int degree = 0, val = 0, res = INT_MAX; unordered_map<int, int> m; for (int num : nums) m[num]++; for (auto it = m.begin(); it != m.end(); it++) { if (it->second > degree) { degree = it->second; } } vector<int> vec; for (auto it = m.begin(); it != m.end(); it++) { if (it->second == degree) { vec.push_back(it->first); } } unordered_map<int, int> n; for (int i = 0; i != nums.size(); i++) n[nums[i]] = i; for (int i = 0; i != vec.size(); i++) { int left = 0, right = n[vec[i]]; bool first = true; for (int j = 0; j != nums.size(); j++) { if (vec[i] == nums[j] && first) { left = j; first = false; } res = min(res, right - left + 1); } } return res; } }; // 279 ms