| 1 | class 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 | } |