MCPcopy
hub / github.com/qiyuangong/leetcode / findShortestSubArray

Method findShortestSubArray

java/697_Degree_of_an_Array.java:2–23  ·  view source on GitHub ↗
(int[] nums)

Source from the content-addressed store, hash-verified

1class Solution {
2 public int findShortestSubArray(int[] nums) {
3 Map<Integer, Integer> left = new HashMap(),
4 right = new HashMap(), count = new HashMap();
5
6 for (int i = 0; i < nums.length; i++) {
7 int x = nums[i];
8 // left most position
9 if (left.get(x) == null) left.put(x, i);
10 // right most position
11 right.put(x, i);
12 count.put(x, count.getOrDefault(x, 0) + 1);
13 }
14
15 int ans = nums.length;
16 int degree = Collections.max(count.values());
17 for (int x: count.keySet()) {
18 if (count.get(x) == degree) {
19 ans = Math.min(ans, right.get(x) - left.get(x) + 1);
20 }
21 }
22 return ans;
23 }
24}

Callers

nothing calls this directly

Calls 3

maxMethod · 0.80
getMethod · 0.45
putMethod · 0.45

Tested by

no test coverage detected