# ［LeetCode］Degree of an Array 数组的度 ［LeetCode］Degree of an Array 数组的度

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.

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;
}
}

0 条评论

## 相关文章

1155

### Java常用集合源码级深度解析

Java集合工具包位于Java.util包下，包含了很多常用的数据结构，如数组、链表、栈、队列、集合、哈希表等。学习Java集合框架下大致可以分为如下五个部分：...

5046

632

36110

38817

1815

1262

### HashSet和HashMap的区别 && HashTable和HashMap的区别

2.Hashtable 中的方法是同步的，而HashMap中的方法在缺省情况下是非同步的。

963

2466

2855