LeetCode-697. Degree of an Array(数组的度)
数组的度
给定一个非空且只包含非负数的整数数组 nums,数组的度的定义是指数组里任一元素出现频数的最大值。
你的任务是在 nums 中找到与 nums 拥有相同大小的度的最短连续子数组,返回其长度。
示例 1:
输入:[1, 2, 2, 3, 1]
输出:2
解释:
输入数组的度是2,因为元素1和2的出现频数最大,均为2.
连续子数组里面拥有相同度的有如下所示:
[1, 2, 2, 3, 1], [1, 2, 2, 3], [2, 2, 3, 1], [1, 2, 2], [2, 2, 3], [2, 2]
最短连续子数组[2, 2]的长度为2,所以返回2.
示例 2:
输入:[1,2,2,3,1,4,2]
输出:6
提示:
nums.length在1到50,000区间范围内。nums[i]是一个在0到49,999范围内的整数。
Degree of an Array
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: nums = [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: nums = [1,2,2,3,1,4,2]
Output: 6
Explanation:
The degree is 3 because the element 2 is repeated 3 times.
So [2,2,3,1,4,2] is the shortest subarray, therefore returning 6.
Constraints:
nums.lengthwill be between1and50,000.nums[i]will be an integer between0and49,999.
解
方法一:哈希表
假设出现次数最多的元素为\(x\),那么所求的数组必然包含所有\(x\),最短的情况就是以\(x\)开始,以\(x\)结束。若出现次数有多个,选取其中最短的一个数组即可。
采用哈希表便于查找,事实上,当测试数据较少的时候,直接使用数组计数的时间开销要小。
代码如下:
class Solution {
public:
int findShortestSubArray(vector<int>& nums) {
unordered_map<int, Info> hash;
int maxDegree = 0;
int minLen = nums.size();
for (int i = 0; i < nums.size(); ++i) {
if (0 == hash.count(nums[i])) {
Info info = {1, i, i + 1};
hash[nums[i]] = info;
} else {
hash[nums[i]].count += 1;
hash[nums[i]].last = i + 1;
}
int degree = hash[nums[i]].count;
int len = hash[nums[i]].last-hash[nums[i]].first;
if(maxDegree < degree){
maxDegree = degree;
minLen = len;
}else if(maxDegree == degree && minLen > len){
minLen = len;
}
}
return minLen;
}
private:
struct Info {
int count;
int first;
int last;
};
// 可以改用向量
};
-------------------------------------------
キミが笑うだけで 全回復だもん!
只要能看到你的笑容 就能完全恢复!
努力做一个灵魂有趣的人!
如果觉得这篇文章对你有小小的帮助的话,记得在右下角点个“推荐”哦,博主在此感谢!( ̄▽ ̄)~*
要是打赏一点就更好了(〜 ̄△ ̄)〜(前微信后支付宝)

浙公网安备 33010602011771号