LeetCode-Degree of an Array
  oAIUsEM70kHw 2023年11月02日 38 0


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 1:

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.

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

题意:给定一个非空且元素非负的一维数组,定义数组的最大频率为元素重复出现的最大次数;现要求找出数组的一个子数组满足其最大频率和原数组相同,并且要求找到的子数组长度最短;

解法:如果[num]为数组中出现次数最多的元素,假设出现次数为[t],那么所找的符合要求的子数组中[num]出现的次数也应当为[t];那么我们可以为每个元素标记他从数组首部开始最早出现的下标位置[leftIndex]和从数组尾部开始最早出现的下标位置[rightIndex],由这两个位置构成的数组的长度为[rightIndex - leftIndex + 1];

class Solution {
public int findShortestSubArray(int[] nums) {
Map<Integer, Integer> leftIndex = new HashMap<>();
Map<Integer, Integer> rightIndex = new HashMap<>();
Map<Integer, Integer> count = new HashMap<>();
int maxFrequency = 0;

for(int i=0; i<nums.length; i++) {
if (leftIndex.get(nums[i]) == null) {
leftIndex.put(nums[i], i);
}
rightIndex.put(nums[i], i);
count.put(nums[i], count.getOrDefault(nums[i], 0) + 1);
maxFrequency = Math.max(maxFrequency, count.get(nums[i]));
}

int result = nums.length;

for(int num : nums) {
if (count.get(num) == maxFrequency) {
result = Math.min(result, rightIndex.get(num) - leftIndex.get(num) + 1);
}
}

return result;
}
}


【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月08日 0

暂无评论

推荐阅读
  YgmmQQ65rPv4   2023年11月19日   13   0   0 Java应用程序
  Y8XIq1u6ceQW   2023年11月19日   25   0   0 Java
  AeUHztwqqxTz   2023年11月02日   23   0   0 Javatomcatapache
  qdH5JHSHCtBs   2023年11月02日   42   0   0 Javadns cache
oAIUsEM70kHw
作者其他文章 更多
最新推荐 更多