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.length150,000 区间范围内。
  • nums[i] 是一个在 049,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.length will be between 1 and 50,000.
  • nums[i] will be an integer between 0 and 49,999.

方法一:哈希表
假设出现次数最多的元素为 x x x,那么所求的数组必然包含所有 x x x,最短的情况就是以 x x 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;
    };
    // 可以改用向量
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值