一刷 07/2022
Version #1 3 HashMaps
Time O(N)
Space O(N)
class Solution {
public int findShortestSubArray(int[] nums) {
// key-number, value-frequency
Map<Integer, Integer> freq = new HashMap<>();
// key-number, value-first,last index of this number
Map<Integer, Integer> leftIndex = new HashMap<>();
Map<Integer, Integer> rightIndex = new HashMap<>();
int maxFreq = 0;
for (int i = 0; i < nums.length; i++) {
int currFreq = freq.getOrDefault(nums[i], 0) + 1;
maxFreq = Math.max(maxFreq, currFreq);
freq.put(nums[i], currFreq);
if (!leftIndex.containsKey(nums[i])) {
leftIndex.put(nums[i], i);
}
rightIndex.put(nums[i], i);
}
int len = nums.length;
for (Map.Entry<Integer, Integer> entry : freq.entrySet()) {
int num = entry.getKey();
if (entry.getValue() == maxFreq) {
len = Math.min(len, rightIndex.get(num) - leftIndex.get(num) + 1);
}
}
return len;
}
}
No comments:
Post a Comment