1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| class Solution { public int findShortestSubArray(int[] nums) { Map<Integer, Integer> map = new HashMap<>(); int max = 0; for(int num : nums){ map.put(num, map.getOrDefault(num, 0) + 1); max = Math.max(max, map.get(num)); }
List<Integer> list = new ArrayList<>(); for (Map.Entry<Integer, Integer> entry : map.entrySet()) { if (entry.getValue() == max) { list.add(entry.getKey()); } }
int ans = Integer.MAX_VALUE; for (Integer num : list) { int i = 0; int j = nums.length -1;
while (nums[i] != num) { i++; }
while (nums[j] != num) { j--; } ans = Math.min(ans, j - i + 1); }
return ans; } }
|