-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Expand file tree
/
Copy path697_Degree_of_an_Array.java
More file actions
24 lines (22 loc) · 759 Bytes
/
Copy path697_Degree_of_an_Array.java
File metadata and controls
24 lines (22 loc) · 759 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
public int findShortestSubArray(int[] nums) {
Map<Integer, Integer> left = new HashMap(),
right = new HashMap(), count = new HashMap();
for (int i = 0; i < nums.length; i++) {
int x = nums[i];
// left most position
if (left.get(x) == null) left.put(x, i);
// right most position
right.put(x, i);
count.put(x, count.getOrDefault(x, 0) + 1);
}
int ans = nums.length;
int degree = Collections.max(count.values());
for (int x: count.keySet()) {
if (count.get(x) == degree) {
ans = Math.min(ans, right.get(x) - left.get(x) + 1);
}
}
return ans;
}
}