zoukankan      html  css  js  c++  java
  • Leetcode697. 数组的度

    697. 数组的度

    Difficulty: 简单

    给定一个非空且只包含非负数的整数数组 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.length 在1到 50,000 区间范围内。
    • nums[i] 是一个在 0 到 49,999 范围内的整数。

    Solution

    Language: java

    ​class Solution {
        public int findShortestSubArray(int[] nums) {
            Map<Integer, int[]> map = new HashMap<>();
            int cnt = 1;
            for(int i=0; i<nums.length; i++){
                if(!map.containsKey(nums[i])){
                    map.put(nums[i], new int[]{i, i, 1});
                }else{
                    int[] t = map.get(nums[i]);
                    t[1] = i;
                    t[2] ++;
                }
                cnt = Math.max(cnt, map.get(nums[i])[2]);
            }
            int[] n = null;
            for(Map.Entry entry : map.entrySet()){
                int[] t = (int[]) entry.getValue();
                if(t[2] == cnt){
                    n = n == null ? t : (n[1] - n[0] > t[1] - t[0] ? t : n);
                }
            }
            return n[1] - n[0] + 1;
        }
    }
    
  • 相关阅读:
    PAT 1025. 反转链表 (25)
    PAT 1024. 科学计数法 (20)
    PAT 1076. Forwards on Weibo (30)
    C++——cout输出小数点后指定位数
    PTA 06-图3 六度空间 (30分)
    PTA 06-图2 Saving James Bond
    PTA
    浙大PTA
    浙大PTA
    随机密码生成
  • 原文地址:https://www.cnblogs.com/liuyongyu/p/14421663.html
Copyright © 2011-2022 走看看