leetcode 697. 数组的度(Degree of an Array)

题目描述:

给定一个非空且只包含非负数的整数数组 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

注意:

  1. nums.length 在1到50,000区间范围内。
  2. nums[i] 是一个在0到49,999范围内的整数。

解法:

class Solution {
public:
    int findShortestSubArray(vector<int>& nums) {
        int degree = 0;
        unordered_map<int, int> mp;
        for(int num : nums){
            if(mp.find(num) == mp.end()){
                mp[num] = 1;
            }else{
                mp[num]++;
            }
        }
        unordered_set<int> cands;
        for(auto it : mp){
            if(it.second > degree){
                degree = it.second;
                cands.clear();
                cands.insert(it.first);
            }else if(it.second == degree){
                cands.insert(it.first);
            }
        }
        unordered_map<int, int> left, right;
        int sz = nums.size();
        for(int i = 0; i < sz; i++){
            if(cands.find(nums[i]) != cands.end()){
                if(left.find(nums[i]) == left.end()){
                    left[nums[i]] = i-1;
                }
                right[nums[i]] = i;
            }
        }
        int res = sz;
        for(int val : cands){
            res = min(res, right[val] - left[val]);
        }
        return res;
    }
};
posted @ 2019-03-27 15:18  zhanzq1  阅读(155)  评论(0)    收藏  举报