Leetcode刷题79-697. 数组的度(C++详细解法!!!)

这是一篇关于LeetCode问题79-697的博客,讨论了如何求解数组的度,即数组中元素的最大出现频率。文章指出该问题并不简单,并分享了作者在解决过程中的思考和收获,提到了使用hash表作为解决方案的关键。

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

Come from : [https://leetcode-cn.com/problems/degree-of-an-array/]

1.Question

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: [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: [1,2,2,3,1,4,2]
Output: 6

Note :

1. nums.length will be between 1 and 50,000.
2. nums[i] will be an integer between 0 and 49,999.

2.Answer

easy 类型题目。是我太菜么。。。这题不简单啊 啊 啊

class Solution {
public:
    int findShortestSubArray(vector<int>& nums) {
        int numsSize = nums.size(), res = INT_MAX, degree = 0;
        unordered_map<int, int> numsCnt;//记录各个数字出现的次数
        unordered_map<int, pair<int, int>> pos;//记录各个数字第一次、最后一次出现的下标
        for (int i = 0; i < numsSize; ++i) {
            if (++numsCnt[nums[i]] == 1) {
                //元素第一次出现
                pos[nums[i]] = {i, i};
            } 
            else {
                //更新最后出现的下标
                pos[nums[i]].second = i;
            }
            //更新出现次数最多的元素次数
            degree = max(degree, numsCnt[nums[i]]);
        }
        for (auto &item : numsCnt) {
            if (degree == item.second) {//此元素出现的次数等于数组的度
                //包含数组中出现的所有item.first需要的最少长度就是[pos[item.first].first, pos[item.first].second],第一次出现、最后一次出现
                res = min(res, pos[item.first].second - pos[item.first].first + 1);
            }
        }
        return res;
    }
};

3.大神们的解决方案

class Solution {
public:
    int findShortestSubArray(vector<int>& nums) {
        int *count= new int[50000];
        int *firstmeet= new int[50000];
        int dim=0;
        int ans=nums.size();
        for(int i=0;i<nums.size();i++)
        {
            int k=nums[i];
            if(count[k]==0)
            {
                firstmeet[k]=i;
            }
            count[k]++;
            if(count[k]>dim)
            {
                dim=count[k];
                ans=i-firstmeet[k]+1;
            }
            else if(count[k]==dim)
            {
                ans=min(ans,i-firstmeet[k]+1);
            }
        }
        return ans;
    }
};

4.我的收获

Fighting~~~
hash表啊 。。。
加强。。。

2019/5/15 胡云层 于南京 79

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值