1. 题目原址
https://leetcode.com/problems/degree-of-an-array/
2. 题目描述
3. 题目大意
给定一个数组,degree为一个数组中的元素出现频率最大值。要求寻找这个数组中出现频率最大的元素的最小距离。
4. 解题思路
- 定义两个数组,一个数组degree存储的是这个元素出现的频率, 另一个数组 head存储的是元素对应的最近的下标位置
- 首先给head数组赋予初值为 -1
- 循环遍历数组,
- 如果head对应的元素的下标值为 -1, 说明之前还没有元素。head存储这个元素对应的下标位置,head的下标是每个元素nums[i]
- 更新degree对应元素的出现频率。
5. AC代码
class Solution {
public int findShortestSubArray(int[] nums) {
int[] head = new int[50001];
int[] degree = new int[50001];
for(int i = 0; i < 50000; i++)
head[i] = -1;
int min = nums.length, max = 1;
for(int i = 0; i < nums.length; i++) {
if(head[nums[i]] == -1)
head[nums[i]] = i;
degree[nums[i]] ++;
if(degree[nums[i]] > max) {
max = degree[nums[i]];
min = i - head[nums[i]] + 1;
} else if(degree[nums[i]] == max && min > i - head[nums[i]] + 1)
min = i - head[nums[i]] + 1;
}
return min;
}
}
6. 相似题型
【1】 53. Maximum Subarray 题目原址:https://leetcode.com/problems/maximum-subarray/