题目
给定一个非空且只包含非负数的整数数组 nums, 数组的度的定义是指数组里任一元素出现频数的最大值。
你的任务是找到与 nums 拥有相同大小的度的最短连续子数组,返回其长度。
示例 1:
输入: [1, 2, 2, 3, 1]
输出: 2
解释:
输入数组的度是2,因为元素1和2的出现频数最大,均为2.
连续子数组里面拥有相同度的有如下所示:
[1, 2, 2, 3, 1], [1, 2, 2, 3], [2, 2, 3, 1], [1, 2, 2], [2, 2, 3], [2, 2]
最短连续子数组[2, 2]的长度为2,所以返回2.
示例 2:
输入: [1,2,2,3,1,4,2]
输出: 6
注意:
nums.length 在1到50,000区间范围内。
nums[i] 是一个在0到49,999范围内的整数。
解题
- 首先找出每个数字出现的次数
- 找出最大的度的数字
- 找出具有最大的度的最小子数组长度, 代码如下:
class Solution {
public int findShortestSubArray(int[] nums) {
Map<Integer, Integer> map = new HashMap<>();
Set<Integer> maxSet = new HashSet<>();
for(int i = 0; i < nums.length; i++){
if(map.containsKey(nums[i])){
map.put(nums[i], map.get(nums[i]) + 1);
} else {
map.put(nums[i], 1);
}
}
int maxDegree = 0;
for(Map.Entry<Integer, Integer> entry : map.entrySet()){
int value = entry.getValue();
if(value == maxDegree){
maxSet.add(entry.getKey());
} else if (value > maxDegree) {
maxDegree = value;
maxSet.clear();
maxSet.add(entry.getKey());
}
}
int minLength = 0;
for(int num : maxSet){
int left = 0;
int right = nums.length - 1;
for(; left < right; left++){
if(nums[left] == num){
break;
}
}
for(; right > left; right--){
if(nums[right] == num){
break;
}
}
if (minLength == 0) {
minLength = right - left + 1;
} else {
minLength = Math.min(right - left + 1, minLength);
}
}
return minLength;
}
}
执行用时: 96 ms, 在Degree of an Array的Java提交中击败了30.73% 的用户
下面这个是在LeetCode上看到的别人的解法, 只用了8ms, 代码如下:
class Solution {
public static int findShortestSubArray(int[] nums) {
//求出nums数组中最大的数
int maxNum = nums[0];
for (int i = 1; i < nums.length; i++) {
maxNum = Math.max(maxNum, nums[i]);
}
//用三个数组分别记录 起始位置,长度,度
int max = 1;//最大的度
int[] start = new int[maxNum + 1];//起始位置
int[] length = new int[maxNum + 1];//长度
int[] count = new int[maxNum + 1];//度
for (int i = 0; i < nums.length; i++) {
count[nums[i]]++;
if (count[nums[i]] == 1) {//记录第一次出现的位置
start[nums[i]] = i;
} else {
length[nums[i]] = i - start[nums[i]] + 1;//记录当前的长度
max = Math.max(count[nums[i]], max);//最大的度
}
}
if (max == 1) {
return 1;
}
int degree = nums.length;//最大的度对应的最小的数组长度
for (int i = 0; i <= maxNum; i++) {
if (count[i] == max) {
degree = Math.min(length[i], degree);
}
}
return degree;
}
}