Leetcode 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
.
nums
will be non-empty and consists of non-negative integers.import java.util.HashMap;
class Solution {
public int findShortestSubArray(int[] nums) {
// Maps to store the first and last positions, and the count of elements
HashMap<Integer, Integer> left = new HashMap<>();
HashMap<Integer, Integer> right = new HashMap<>();
HashMap<Integer, Integer> count = new HashMap<>();
int degree = 0;
for (int i = 0; i < nums.length; i++) {
int num = nums[i];
if (!left.containsKey(num)) {
left.put(num, i);
}
right.put(num, i);
count.put(num, count.getOrDefault(num, 0) + 1);
degree = Math.max(degree, count.get(num));
}
int minLength = nums.length;
for (Integer num : count.keySet()) {
if (count.get(num) == degree) {
minLength = Math.min(minLength, right.get(num) - left.get(num) + 1);
}
}
return minLength;
}
}
left
, right
, count
).This approach efficiently calculates the required smallest subarray with a degree equal to that of the array with optimal time and space usage.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?