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.數組

輸入一個正整數數組,這個數組的「度」就是數組中任意元素出現的最大次數。而咱們要找出這個數組的一個子數組,知足「度」等於整個數組的「度」的同時,保證子數組的長度最小,返回這個最小的長度。

Example 1:
Input: [1, 2, 2, 3, 1]
Output: 2
Explanation:
輸入數組的度爲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。
Example 2:
Input: [1,2,2,3,1,4,2]
Output: 6this

想法

  • 想盡可能減小遍歷的次數,所以在第一趟遍歷中咱們即保存了全部元素出現的次數,也保存了每一個元素出現的範圍。
  • 由於涉及到對元素出現次數的計數,所以咱們採用HashMap來實現。一個HashMap保存元素的值和出現的次數。另外一個Hashmap保存元素的值和元素出現的範圍,用int[] numRange數組表示,numRange[0]表示第一次出現的位置,numRange[1]表示最後出現的位置。
  • 最後遍歷HashMap,獲取知足「度」相等的最小子數組長度。

解法

public int findShortestSubArray(int[] nums) {
        int minLength = nums.length;
        int degree = 0;
        HashMap<Integer, Integer> count = new HashMap<Integer,Integer>();
        HashMap<Integer,Integer[]> index = new  HashMap<Integer,Integer[]>();
        
        for(int i=0;i<nums.length;i++){
            count.put(nums[i], count.getOrDefault(nums[i], 0) + 1);
            degree = Math.max(degree, count.get(nums[i]));
            
            if(index.get(nums[i]) == null){
                index.put(nums[i],new Integer[2]);
            }
            Integer[] numRange = index.get(nums[i]);
            if(numRange[0] == null)numRange[0] = i;
            numRange[1] = i;
        }
        
        for(Map.Entry<Integer, Integer> entry : count.entrySet()){
            if(entry.getValue() != degree){
                continue;
            }
            Integer[] range = index.get(entry.getKey());
            minLength = Math.min(minLength, range[1]-range[0]+1);
        }
        
        return minLength;
    }
相關文章
相關標籤/搜索