问题描述:
Give a string s
, count the number of non-empty (contiguous) substrings that have the same
number of 0's and 1's, and all the 0's and all the 1's in these substrings are grouped consecutively.
Substrings that occur multiple times are counted the number of times they occur.
示例:
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.
Input: [1,2,2,3,1,4,2] Output: 6
问题分析:
统计每个元素出现的次数,每个元素开始出现的位置和最后出现的位置,找到出现次数最多的元素的在数组中的最短长度即可。
过程详见代码:
class Solution {
public:
int findShortestSubArray(vector<int>& nums) {
unordered_map<int, pair<int, int>> m1;
unordered_map<int, int> m2;
int count = 0,res = nums.size();
for (int i = 0; i < nums.size(); i++)
{
m2[nums[i]]++;
if (m1.find(nums[i]) == m1.end()) m1[nums[i]] = pair<int, int>(i, i);
else m1[nums[i]].second = i;
if (m2[nums[i]] > count) count = m2[nums[i]];
}
for (auto num : m2)
{
if (count == num.second)
{
res = min(res, m1[num.first].second - m1[num.first].first + 1);
}
}
return res;
}
};