forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDegree of an Array.java
34 lines (29 loc) · 1.02 KB
/
Degree of an Array.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class Solution {
public int findShortestSubArray(int[] nums) {
int ans = Integer.MAX_VALUE;
Map<Integer, Integer> count = new HashMap<>();
Map<Integer, Integer> startIndex = new HashMap<>();
Map<Integer, Integer> endIndex = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
count.put(nums[i], count.getOrDefault(nums[i], 0) + 1);
}
for (int i = 0; i < nums.length; i++) {
int no = nums[i];
if (!startIndex.containsKey(no)) {
startIndex.put(no, i);
}
endIndex.put(no, i);
}
int degree = Integer.MIN_VALUE;
for (Integer key : count.keySet()) {
degree = Math.max(degree, count.get(key));
}
for (Integer key : count.keySet()) {
if (count.get(key) == degree) {
int arraySize = endIndex.get(key) - startIndex.get(key) + 1;
ans = Math.min(ans, arraySize);
}
}
return ans;
}
}