-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDegreeOfArray.java
More file actions
36 lines (30 loc) · 1013 Bytes
/
DegreeOfArray.java
File metadata and controls
36 lines (30 loc) · 1013 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
25
26
27
28
29
30
31
32
33
34
35
36
package array;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
/**
* Description: https://leetcode.com/problems/degree-of-an-array
* Difficulty: Easy
* Time complexity: O(n)
* Space complexity: O(n)
*/
public class DegreeOfArray {
public int findShortestSubArray(int[] nums) {
Map<Integer, Integer> first = new HashMap<>();
Map<Integer, Integer> last = new HashMap<>();
Map<Integer, Integer> freqMap = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
first.putIfAbsent(nums[i], i);
last.put(nums[i], i);
freqMap.merge(nums[i], 1, Integer::sum);
}
int arrayDegree = Collections.max(freqMap.values());
int shortest = Integer.MAX_VALUE;
for (int num : freqMap.keySet()) {
if (freqMap.get(num) == arrayDegree) {
shortest = Math.min(shortest, last.get(num) - first.get(num) + 1);
}
}
return shortest;
}
}