LeetCode#697: Degree of an Array

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_38283262/article/details/83029652

Description

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

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

Solution

此题的意思是在数组中找到数字的最高频率作为degree,然后在此数组中找到一个最短的子数组使它拥有相同的degree,返回该子数组的长度。也就是说,在子数组中必须包含出现频率最高的所有数字中的至少一个数字,并且这个数字全部都在子数组中。因此,我们就需要记录数字的第一次出现位置与最后一次出现位置,位置差最短的子数组即为目标子数组。

以下代码使用了三个map,分别记录数字第一次出现的位置、数字最后一次出现位置与数字的出现次数。

class Solution {
    public int findShortestSubArray(int[] nums) {
        HashMap<Integer, Integer> left = new HashMap<>();
        HashMap<Integer, Integer> right = new HashMap<>();
        HashMap<Integer, Integer> count = new HashMap<>();
        for(int i = 0; i < nums.length; i++) {
        	int num = nums[i];
        	if(left.get(num) == null)
        		left.put(num, i);
        	right.put(num, i);
        	count.put(num, count.getOrDefault(num, 0)+1);
        }
        
        int degree = Collections.max(count.values());
        int shortest = Integer.MAX_VALUE;
        for(int num : count.keySet()) {
        	if(count.get(num) == degree) {
        		shortest = Math.min(shortest, right.get(num) - left.get(num) + 1);
        	}
        }
        return shortest;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_38283262/article/details/83029652