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