-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSolution.java
More file actions
30 lines (27 loc) · 936 Bytes
/
Copy pathSolution.java
File metadata and controls
30 lines (27 loc) · 936 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
import java.util.HashMap;
import java.util.Map;
class Solution
{
public int findShortestSubArray(int[] nums)
{
final Map<Integer, Integer> startIdx = new HashMap<>(), endIdx = new HashMap<>(), counts = new HashMap<>();
for (int i = 0; i < nums.length; i++)
{
int num = nums[i];
startIdx.putIfAbsent(num, i);
endIdx.put(num, i);
counts.put(num, counts.getOrDefault(num, 0) + 1);
}
int shortestLen = Integer.MAX_VALUE, max = 0;
for (Map.Entry<Integer, Integer> entry : counts.entrySet())
{
if (max <= entry.getValue())
{
int len = endIdx.get(entry.getKey()) - startIdx.get(entry.getKey()) + 1;
shortestLen = max != entry.getValue() ? len : Math.min(shortestLen, len);
max = entry.getValue();
}
}
return shortestLen;
}
}