给定一个非空且只包含非负数的整数数组 nums, 数组的度的定义是指数组里任一元素出现频数的最大值。
你的任务是找到与 nums 拥有相同大小的度的最短连续子数组,返回其长度。
示例 1:
输入: [1, 2, 2, 3, 1]
输出: 2
解释: 输入数组的度是2,因为元素1和2的出现频数最大,均为2. 连续子数组里面拥有相同度的有如下所示: [1, 2, 2, 3, 1], [1, 2, 2, 3], [2, 2, 3, 1], [1, 2, 2], [2, 2, 3], [2, 2] 最短连续子数组[2, 2]的长度为2,所以返回2.
示例 2:
输入: [1,2,2,3,1,4,2]
输出: 6
注意:
nums.length 在1到50,000区间范围内。
nums[i] 是一个在0到49,999范围内的整数。
解答:
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
| class Solution { public int findShortestSubArray(int[] nums) { HashMap<Integer, Integer> intStartIndex = new HashMap<>(), intLastIndex = new HashMap<>(), intCnt = new HashMap<>(); List<Integer> list = new ArrayList<>(); int max = 0; for (int i = 0; i < nums.length; i++) { Integer n = nums[i]; if (!intStartIndex.containsKey(n)) intStartIndex.put(n, i); intLastIndex.put(n, i); intCnt.put(n, intCnt.getOrDefault(n, 0) + 1); int cnt = intCnt.get(n); if (cnt > max) { max = cnt; list.clear(); } if (cnt == max) list.add(n);
} int ret = 0; for (int i = 0; i < list.size(); i++) { int tmp = list.get(i); int candidate = intLastIndex.get(tmp) - intStartIndex.get(tmp) + 1; if (candidate < ret || ret == 0) ret = candidate; } return ret; } }
|