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;
        }
    }
    
  • 相关阅读:
    Eclipse无法正常启动,弹出对话框内容为 A Java Runtime...
    redis入门常用的命令操作(总结 一)
    初级工程师的面试
    公司金融学理论--MM理论
    以太坊开发环境搭建
    如何以树形结构显示文件目录结构
    Neural Network Basics
    大前端公共知识梳理
    出SS表
    iOS weak关键字
  • 原文地址:https://www.cnblogs.com/liuyongyu/p/14421663.html
Copyright © 2011-2022 走看看