leetcode 697. Degree of an Array数组的度

来源:互联网 发布:知乎成都 编辑:程序博客网 时间:2024/06/05 03:41

问题描述:

  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;             }}