• 697. 数组的度


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

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/degree-of-an-array
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

     py

    class Solution:
        def findShortestSubArray(self, nums: List[int]) -> int:
            cnt=collections.Counter(nums)
            maxcnt=max(list(cnt.values()))#get the degree of nums
            begin_end={}#get the begin & end index for x in nums
    
            for i,x in enumerate(nums):
                if x not in begin_end:
                    begin_end[x]=[i,i]#get the begin_index
                else:
                    begin_end[x]=[begin_end[x][0],i]#update the end_index
            
            res=len(nums)+1
            for x in nums:
                if cnt[x]==maxcnt:
                    res=min(begin_end[x][1]-begin_end[x][0]+1,res)#minimize the end_index-begin_index
            return res

     Java

    class Solution {
        public int findShortestSubArray(int[] nums) {
            int[] L=new int[50000];
            Arrays.fill(L,-1);
            int[] R=new int[50000];
            int[] cnt=new int[50000];
            int maxcnt=0;
            int n=nums.length;
            int res=n+1;
    
            for(int i=0;i<n;i++){
                if(L[nums[i]]==-1)L[nums[i]]=i;
                else R[nums[i]]=i;
                cnt[nums[i]]++;
                maxcnt=Math.max(maxcnt,cnt[nums[i]]);
            }
    
            for(int x:nums){
                if(cnt[x]==maxcnt)
                    res=Math.min(res,R[x]-L[x]+1);
            }
    
            return res;
        }
    }
  • 相关阅读:
    判断某个元素是否显示/隐藏
    文件file
    文件上传原理--FileReader
    angular搭建
    判断滚动条滚到底部
    bugDone
    webstorm界面主题
    自定义滚动条
    用电脑免费给手机发短信(转)
    c++ 面试常见问题
  • 原文地址:https://www.cnblogs.com/xxxsans/p/13833978.html
Copyright © 2020-2023  润新知