LeetCode#697: Degree of an Array
阿新 • • 發佈:2018-12-14
Description
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
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.
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.
Solution
此題的意思是在陣列中找到數字的最高頻率作為degree,然後在此陣列中找到一個最短的子陣列使它擁有相同的degree,返回該子陣列的長度。也就是說,在子陣列中必須包含出現頻率最高的所有數字中的至少一個數字,並且這個數字全部都在子陣列中。因此,我們就需要記錄數字的第一次出現位置與最後一次出現位置,位置差最短的子陣列即為目標子陣列。
以下程式碼使用了三個map,分別記錄數字第一次出現的位置、數字最後一次出現位置與數字的出現次數。
class Solution {
public int findShortestSubArray(int[] nums) {
HashMap<Integer, Integer> left = new HashMap<>();
HashMap<Integer, Integer> right = new HashMap<>();
HashMap<Integer, Integer> count = new HashMap<>();
for(int i = 0; i < nums.length; i++) {
int num = nums[i];
if(left.get(num) == null)
left.put(num, i);
right.put(num, i);
count.put(num, count.getOrDefault(num, 0)+1);
}
int degree = Collections.max(count.values());
int shortest = Integer.MAX_VALUE;
for(int num : count.keySet()) {
if(count.get(num) == degree) {
shortest = Math.min(shortest, right.get(num) - left.get(num) + 1);
}
}
return shortest;
}
}