forked from codedecks-in/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDegree-of-an-Array.java
35 lines (30 loc) · 893 Bytes
/
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
35
/*
*
*
*
*/
class Solution {
public int findShortestSubArray(int[] nums) {
Map<Integer, Integer> left = new HashMap(), right = new HashMap(), count = new HashMap();
//find the leftmost and rightmost index of each characters
for(int i= 0;i<nums.length; i++)
{
int x =nums[i];
if(left.get(x) == null)
left.put(x, i);
right.put(x, i);
count.put(x, count.getOrDefault(x, 0) + 1);
}
int ans = nums.length;
int degree = Collections.max(count.values());
//find min distance between subarrays with same degree
for(int x: count.keySet())
{
if(count.get(x) == degree)
{
ans = Math.min(ans , right.get(x) - left.get(x) + 1);
}
}
return ans;
}
}