Degree of an Array LeetCode solution in Java

1
class Solution {
2
public int findShortestSubArray(int[] nums) {
3
// The int is an array of [firstEncounter, lastEncounter, frequency]
4
HashMap<Integer, int[]> map = new HashMap<>();
5
for (int i = 0; i < nums.length; i++) {
6

7
// If the key does not exist in the map, we put it with the first encounter and last encounter
8
// set to the current position, 'i', and the freqency 1
9
if (!map.containsKey(nums[i])) {
10
map.put(nums[i], new int[] {i, i, 1});
11
}
12

13
// If it does exist, we update the last encounter to the current position and we increase the
14
// frequency by 1
15
else {
16
int[] arr = map.get(nums[i]);
17
arr[1] = i;
18
arr[2]++;
19
map.put(nums[i], arr);
20
}
21
}
22
// Maximim frequency
23
int maxFreq = Integer.MIN_VALUE;
24

25
// Minimum distance
26
int minDist = Integer.MAX_VALUE;
27

28
// Going through all the values of the HashMap
29
for (int[] value : map.values()) {
30
// value[0] = the first encounter index
31
// value[1] = the last encounter index
32
// value[2] = frequency
33

34
// If the frecuency is greater than the maxFreq, then we update it and also set the minDist
35
if (value[2] > maxFreq) {
36
maxFreq = value[2];
37
minDist = value[1] - value[0] + 1;
38
}
39

40
// If the frecuency is equal to the current max, we take the minimum between the exiting
41
// minDist and the minimum distance for the current value
42
else if (value[2] == maxFreq) {
43
minDist = Math.min(minDist, value[1] - value[0] + 1);
44
}
45
}
46
return minDist;
47
}
48
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0