697. 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: [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: [1,2,2,3,1,4,2]
Output: 6
Note:
nums.length
will be between 1 and 50,000.
nums[i]
will be an integer between 0 and 49,999.
My Solutions:
用一个Hashmap存上key为数字,value为int【】的数组,数组储存了最前的index,最后的index,和key的个数。
class Solution {
public int findShortestSubArray(int[] nums) {
if (nums == null || nums.length == 0) return 0;
Map<Integer, int[]> map = new HashMap<>();
int degree = 1;
for (int i = 0; i < nums.length; i++) {
if (!map.containsKey(nums[i])) {
map.put(nums[i], new int[]{i, i, 1}); //start index, end index, frequency
} else {
int[] vars = map.get(nums[i]);
vars[1] = i; //更新end index
vars[2]++; //更新frequency
degree = Math.max(degree, vars[2]); //更新degree
}
}
int res = nums.length;
for (int[] values : map.values()) {
if (values[2] == degree) {
res = Math.min(res, values[1] - values[0] + 1); //values[1] - values[0] + 1 是subarray的长度
}
}
return res;
}
}
Last updated