[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: nums = [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:

Input: nums = [1,2,2,3,1,4,2]
Output: 6
Explanation: 
The degree is 3 because the element 2 is repeated 3 times.
So [2,2,3,1,4,2] is the shortest subarray, therefore returning 6.

Constraints:

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

数组的度。

给定一个非空且只包含非负数的整数数组 nums,数组的度的定义是指数组里任一元素出现频数的最大值。

你的任务是在 nums 中找到与 nums 拥有相同大小的度的最短连续子数组,返回其长度。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/degree-of-an-array
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路是用两个 hashmap,一个记录数字的出现次数 count,一个记录每个不同数字最早出现的坐标 first。当每次发现一个出现次数最多的数字的时候,这个数字会更新整个 input 数组的度 degree,此时我们可以看一下当前位置 i 和这个元素第一次出现的 index 的距离。反复这样找,看看全局长度最短的距离是多少。

时间O(n)

空间O(n)

Java实现

 1 class Solution {
 2     public int findShortestSubArray(int[] nums) {
 3         Map<Integer, Integer> count = new HashMap<>();
 4         Map<Integer, Integer> first = new HashMap<>();
 5         int res = 0;
 6         int degree = 0;
 7         for (int i = 0; i < nums.length; i++) {
 8             first.putIfAbsent(nums[i], i);
 9             count.put(nums[i], count.getOrDefault(nums[i], 0) + 1);
10             if (count.get(nums[i]) > degree) {
11                 degree = count.get(nums[i]);
12                 res = i - first.get(nums[i]) + 1;
13             } else if (count.get(nums[i]) == degree) {
14                 res = Math.min(res, i - first.get(nums[i]) + 1);
15             }
16         }
17         return res;
18     }
19 }

 

LeetCode 题目总结

posted @ 2020-06-10 10:09  CNoodle  阅读(215)  评论(0编辑  收藏  举报