题目原址
https://leetcode.com/problems/degree-of-an-array/description/
题目描述
Example1:
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.
Example2:
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.
解题思路
- 定义三个HashMap:count –>统计同一数组元素出现的次数;starts –> 统计第一次出现该元素的下标;ends–>统计所有元素最后一次出现的下标
- 第一次遍历:
- 第一步:如果在count中不存在该元素,则将它存入count和starts中,否则执行第二步
- 第二步:将元素存入ends中,将元素值作为键,下标值作为值。
- 第三步:更改元素的出现次数,按照元素值更改出现的次数。
- 第四步:修改max,max指现有的元素重复出现的最多的次数
- 第二次遍历:
- 使用增强for循环,将count中的所有键取出来,判断键对应的值是否等于max,如果等于max就找到相邻的元素的最小值。
AC代码
class Solution {
public int findShortestSubArray(int[] nums) {
int length = nums.length;
Map<Integer,Integer> count= new HashMap<Integer,Integer>();
Map<Integer,Integer> starts = new HashMap<Integer,Integer>();
Map<Integer,Integer> ends = new HashMap<Integer,Integer>();
int max = Integer.MIN_VALUE;
for(int i = 0; i<length; i++) {
if(!(count.containsKey(nums[i]))) {
count.put(nums[i], 0);
starts.put(nums[i], i);
}
ends.put(nums[i], i);
count.put(nums[i], count.get(nums[i])+1);
max = Math.max(max, count.get(nums[i]));
}
int min = Integer.MAX_VALUE;
for(Integer key:count.keySet()) {
if(count.get(key) == max) {
min = Math.min(min, ends.get(key) - starts.get(key) + 1);
}
}
return min;
}
}