leetcode 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.


这里写图片描述

Note:

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

思路:

  首先要求出这个数组的度,需要遍历整个数组,将元素的值和对应出现的次数以键值对的形式放入map中存储,同时还要记录每个元素第一次出现的索引值和最后一次出现的索引值,最后得到同一元素出现的最多次数。然后比较每个出现最多次数的元素的首尾差值长度,求最小值。

代码:

class Solution {
    public int findShortestSubArray(int[] nums) {
        if(nums.length == 0) return 0;
        int max = 1;
        int min = 50000;
        HashMap<Integer, Integer> map = new HashMap<>();
        HashMap<Integer, Integer> firstPoint = new HashMap<>();
        HashMap<Integer, Integer> lastPoint = new HashMap<>();
        List<Integer> list = new ArrayList<Integer>();
        for(int i = 0; i < nums.length; i++){
            if(map.containsKey(nums[i])){
                map.replace(nums[i], map.get(nums[i])+1);
                lastPoint.replace(nums[i], i);
                if(map.get(nums[i]) > max)
                    max = map.get(nums[i]);
            }
            else{
                map.put(nums[i], 1);
                firstPoint.put(nums[i], i);
                lastPoint.put(nums[i], i);
            }           
        }
        for(Integer it : map.keySet()){
            if(map.get(it).equals(max))
                list.add(it);
        }
        for(Integer it : list){
            int a = lastPoint.get(it) - firstPoint.get(it) + 1;
            min = a > min ? min : a;
        }       
        return min;         
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值