leetcode-697-easy
Degree of an Array
Given a non-empty array of non-negative integers nums, the degree of this array is defined as the maximum frequency of any one of its elements.
Your task is to find the smallest possible length of a (contiguous) subarray of nums, that has the same degree as nums.
Example 1:
Input: nums = [1,2,2,3,1]
Output: 2
Explanation:
The input array has a degree of 2 because both elements 1 and 2 appear twice.
Of the subarrays that have the same degree:
[1, 2, 2, 3, 1], [1, 2, 2, 3], [2, 2, 3, 1], [1, 2, 2], [2, 2, 3], [2, 2]
The shortest length is 2. So return 2.
Example 2:
Input: nums = [1,2,2,3,1,4,2]
Output: 6
Explanation:
The degree is 3 because the element 2 is repeated 3 times.
So [2,2,3,1,4,2] is the shortest subarray, therefore returning 6.
Constraints:
nums.length will be between 1 and 50,000.
nums[i] will be an integer between 0 and 49,999.
思路一:没有想到什么好算法,用的是最简单粗暴的模式,先用 map 统计最多的数字,然后计算这些数字的最小间距,最后取最小间距的那个数字
public int findShortestSubArray(int[] nums) {
Map<Integer, Integer> map = new HashMap<>();
for (int num : nums) {
map.compute(num, (k, v) -> v == null ? 1 : v + 1);
}
List<Integer> maxNumList = new ArrayList<>();
int max = 0;
for (Map.Entry<Integer, Integer> e : map.entrySet()) {
if (e.getValue() > max) {
maxNumList.clear();
maxNumList.add(e.getKey());
max = e.getValue();
} else if (e.getValue() == max) {
maxNumList.add(e.getKey());
}
}
int min = Integer.MAX_VALUE;
for (Integer num : maxNumList) {
int low = 0;
int high = nums.length - 1;
while (low < nums.length && nums[low] != num) {
low++;
}
while (high > 0 && nums[high] != num) {
high--;
}
min = Math.min(min, high - low + 1);
}
return min;
}
思路二:看了一下官方的题解,发现用可以用 map 存储 int[] 值,int[] 直接存储数字下标就行,速度会快很多

浙公网安备 33010602011771号