forked from varunu28/LeetCode-Java-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDegree of an array.java
More file actions
42 lines (36 loc) · 1.14 KB
/
Degree of an array.java
File metadata and controls
42 lines (36 loc) · 1.14 KB
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
37
38
39
40
41
42
class Solution {
public int findShortestSubArray(int[] nums) {
Map<Integer, Entry> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
if (map.containsKey(nums[i])) {
map.get(nums[i]).degree++;
map.get(nums[i]).endIdx = i;
}
else {
map.put(nums[i], new Entry(1, i, i));
}
}
int res = Integer.MAX_VALUE;
int degree = Integer.MIN_VALUE;
for (Entry entry : map.values()) {
if (degree < entry.degree) {
degree = entry.degree;
res = entry.endIdx - entry.startIdx + 1;
}
else if (degree == entry.degree) {
res = Math.min(entry.endIdx - entry.startIdx + 1, res);
}
}
return res;
}
class Entry {
int degree;
int startIdx;
int endIdx;
public Entry(int degree, int startIdx, int endIdx) {
this.degree = degree;
this.startIdx = startIdx;
this.endIdx = endIdx;
}
}
}