MCPcopy Create free account
hub / github.com/codedecks-in/LeetCode-Solutions / findShortestSubArray

Method findShortestSubArray

Java/Degree-of-an-Array.java:8–34  ·  view source on GitHub ↗
(int[] nums)

Source from the content-addressed store, hash-verified

6
7class Solution {
8 public int findShortestSubArray(int[] nums) {
9 Map<Integer, Integer> left = new HashMap(), right = new HashMap(), count = new HashMap();
10
11 //find the leftmost and rightmost index of each characters
12 for(int i= 0;i<nums.length; i++)
13 {
14 int x =nums[i];
15 if(left.get(x) == null)
16 left.put(x, i);
17
18 right.put(x, i);
19 count.put(x, count.getOrDefault(x, 0) + 1);
20 }
21
22 int ans = nums.length;
23 int degree = Collections.max(count.values());
24
25 //find min distance between subarrays with same degree
26 for(int x: count.keySet())
27 {
28 if(count.get(x) == degree)
29 {
30 ans = Math.min(ans , right.get(x) - left.get(x) + 1);
31 }
32 }
33 return ans;
34 }
35}

Callers

nothing calls this directly

Calls 2

getMethod · 0.45
putMethod · 0.45

Tested by

no test coverage detected