leetcode 697

697. 数组的度

难度简单405收藏分享切换为英文接收动态反馈

给定一个非空且只包含非负数的整数数组 nums,数组的  的定义是指数组里任一元素出现频数的最大值。

你的任务是在 nums 中找到与 nums 拥有相同大小的度的最短连续子数组,返回其长度。

示例 1:

输入:nums = [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:

输入:nums = [1,2,2,3,1,4,2]
输出:6
解释:
数组的度是 3 ,因为元素 2 重复出现 3 次。
所以 [2,2,3,1,4,2] 是最短子数组,因此返回 6 。

提示:

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

通过次数73,696提交次数122,404

解题:看明白了就不难,总结一下就是要找出数组的众数,并且还有找出众数在数组中第一次出现和最后一次出现的位置,两个位置组成区间长度就是答案, 如果众数不止一个,那么要取区间长度最短那个

class Solution {
public:
    int findShortestSubArray(vector<int>& nums) {
        // 0. if length== 0 ,return 1
        if(nums.size()==1)
            return 1;
         // 1.find max-value in nums, for alloc count[] memory
        int maxvalue =0;
        for(auto i:nums)
        {
            maxvalue=max(maxvalue,i);
        }
        maxvalue=max(maxvalue+1,(int)nums.size()+1);
        // 2.need a count[],length == maxvalue
        vector<int> count(maxvalue,0);
        // 3. count each num 
        for(auto i:nums)
        {
            count[i]++;
        }
        int maxcount=0;
        for(int i=0;i<maxvalue;i++)
        {
            maxcount=max(maxcount,count[i]);
        }
        // 4.1 if maxcount==1 
        if(maxcount==1)
            return 1;
        // 4.2 else maxcount>1 and consider modal num not only one!
        vector<int> tempnums;
        for(int i=0;i<maxvalue;i++)
        {
            if(count[i]==maxcount)
            {
                tempnums.emplace_back(i);
            }
        }
        // 5. find the Shortest interval
        int reti=maxvalue;
        for(auto i:tempnums)
        {
            int begin=0,end=nums.size()-1;
            while(begin<end)
            {
                if(nums[begin]==i && nums[end]==i)
                {
                    reti=min(end-begin+1,reti);
                    break;
                }
                else if(nums[begin]==i)
                {
                    end--;
                }
                else if(nums[end]==i)
                {
                    begin++;
                }
                else
                {
                    begin++;
                    end--;
                }
            }
        }
        return reti;
    }
};

执行结果:

通过

显示详情

添加备注

执行用时:28 ms, 在所有 C++ 提交中击败了86.79%的用户

内存消耗:25.4 MB, 在所有 C++ 提交中击败了34.90%的用户

通过测试用例:89 / 89

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值