# ［LeetCode］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: [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.

Java

class Solution {
public int findShortestSubArray(int[] nums) {
Map<Integer, Integer> left = new HashMap();
Map<Integer, Integer> right = new HashMap();
Map<Integer, Integer> count = new HashMap();

for(int i=0; i < nums.length; i++ ){
if(!left.containsKey(nums[i]))
left.put(nums[i], i);
right.put(nums[i], i);
count.put(nums[i], count.getOrDefault(nums[i],0)+1);
}

int degree = Collections.max(count.values());
int length = Integer.MAX_VALUE;
for(int i=0; i<nums.length; i++){
if(count.get(nums[i])==degree){
length = Math.min(length, right.get(nums[i]) - left.get(nums[i]) + 1);
}
}
return length;
}
}


|
1天前
|

【Leetcode刷题Python】852. 山脉数组的峰顶索引

7 0
|
1天前
|

【Leetcode刷题Python】33. 搜索旋转排序数组

5 0
|
1天前
|

【Leetcode刷题Python】34. 在排序数组中查找元素的第一个和最后一个位置(二分查找)

7 0
|
25天前
|

Array数组reduce方法与数组累加、去重
【7月更文挑战第12天】
14 1
|
28天前
|

31 0
|
1月前
|
JavaScript API 索引
JS【详解】Set 集合 （含 Set 集合和 Array 数组的区别，Set 的 API，Set 与 Array 的性能对比，Set 的应用场景）
JS【详解】Set 集合 （含 Set 集合和 Array 数组的区别，Set 的 API，Set 与 Array 的性能对比，Set 的应用场景）
35 0
|
1月前
|

let array = [{id:‘001‘,name:‘小新‘,age:5},{ id:‘002‘,name:‘小葵‘]这样数据如何遍历，拿到其中一个值，数组中装对象如何获取其中一个固定的值
let array = [{id:‘001‘,name:‘小新‘,age:5},{ id:‘002‘,name:‘小葵‘]这样数据如何遍历，拿到其中一个值，数组中装对象如何获取其中一个固定的值
20 0
|
1月前
|

16 0
|
3月前
|
Python

40 3
|
3月前
|
JavaScript 前端开发

66 0