Skip to content

Commit 9dd121f

Browse files
Sean PrashadSean Prashad
authored andcommitted
Add 697_Degree_of_an_Array.java
1 parent 2a521c2 commit 9dd121f

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

Arrays/697_Degree_of_an_Array.java

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
class Solution {
2+
public int findShortestSubArray(int[] nums) {
3+
Map<Integer, int[]> idxMap = new HashMap<>();
4+
List<Integer> mostFreq = new ArrayList<>();
5+
6+
int maxFreq = 0, result = Integer.MAX_VALUE;
7+
8+
for (int i = 0; i < nums.length; i++) {
9+
int[] indices = idxMap.getOrDefault(nums[i], new int[2]);
10+
11+
if (idxMap.containsKey(nums[i])) {
12+
indices[0]++;
13+
} else {
14+
indices[0] = 1;
15+
indices[1] = i;
16+
}
17+
18+
idxMap.put(nums[i], indices);
19+
20+
if (indices[0] > maxFreq) {
21+
maxFreq = indices[0];
22+
result = i - indices[1] + 1;
23+
} else if (indices[0] == maxFreq) {
24+
result = Math.min(result, i - indices[1] + 1);
25+
}
26+
}
27+
28+
return result;
29+
}
30+
}

0 commit comments

Comments
 (0)