前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >[LeetCode]Degree of an Array 数组的度 [LeetCode]Degree of an Array 数组的度

[LeetCode]Degree of an Array 数组的度 [LeetCode]Degree of an Array 数组的度

作者头像
尾尾部落
发布2018-09-04 14:37:53
5520
发布2018-09-04 14:37:53
举报
文章被收录于专栏:尾尾部落

链接:https://leetcode.com/problems/degree-of-an-array/description/ 难度:Easy 题目:697. Degree of an Array 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:

代码语言:javascript
复制
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:

代码语言:javascript
复制
Input: [1,2,2,3,1,4,2]
Output: 6

Note:

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

翻译:给定一个非空非负的整型数组,定义数组的度为数组中元素出现的最大次数。任务是找出度和数组的度相同的最小子串

思路:记录下第一次出现和最后一次出现的位置就好了,两者相减就是最短长度。对于有多个出现次数最多元素的情况,只需要找出这些元素的最短子串中最小的就好了。

参考代码: Java

代码语言:javascript
复制
class Solution {
    public int findShortestSubArray(int[] nums) {
        Map<Integer, Integer> left = new HashMap();
        Map<Integer, Integer> right = new HashMap();
        Map<Integer, Integer> count = new HashMap();

        for(int i=0; i < nums.length; i++ ){
            if(!left.containsKey(nums[i]))
                left.put(nums[i], i);
            right.put(nums[i], i);
            count.put(nums[i], count.getOrDefault(nums[i],0)+1);
        }

        int degree = Collections.max(count.values());
        int length = Integer.MAX_VALUE;
        for(int i=0; i<nums.length; i++){
            if(count.get(nums[i])==degree){
                length = Math.min(length, right.get(nums[i]) - left.get(nums[i]) + 1);
            }
        }
        return length;
    }   
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档