Degree of an Array问题及解法

本文介绍了一种算法,用于解决寻找数组中最短的、具有最大出现次数的子数组问题。该算法通过统计每个元素的出现频率及位置,确定出现频率最高的元素及其最短子数组长度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题描述:

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;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值