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.
題目標簽:Array
題目給了我們一個 nums array, 讓我們首先找到 出現最多次數的數字(可能多於1個),然后在這些數字中,找到一個 長度最小的 數字。返回它的長度。
比較直接的想法就是,既然我們首先要知道每一個數字出現的次數,那么就利用HashMap,而且我們還要知道 這個數字的最小index 和最大index,那么也可以存入map記錄。
設一個HashMap<Integer, int[]> map, key 就是 num,value 就是int[3]: int[0] 記錄 firstIndex; int[1] 記錄 lastIndex; int[2] 記錄次數。
這樣的話,我們需要遍歷兩次:
第一次遍歷nums array:記錄每一個數字的 firstIndex, lastIndex, 出現次數; 還要記錄下最大的出現次數。
第二次遍歷map key set:當key (num) 的次數等於最大次數的時候,記錄最小的長度。(lastIndex - firstIndex + 1)。
Java Solution:
Runtime beats 74.35%
完成日期:10/24/2017
關鍵詞:Array
關鍵點:HashMap<num, [firstIndex, lastIndex, Occurrence]>
1 class Solution 2 { 3 public int findShortestSubArray(int[] nums) 4 { 5 HashMap<Integer, int[]> map = new HashMap<>(); 6 int maxFre = 0; 7 int minLen = Integer.MAX_VALUE; 8 9 // first nums iteration: store first index, last index, occurrence and find out the maxFre 10 for(int i=0; i<nums.length; i++) 11 { 12 if(map.containsKey(nums[i])) // num is already in map 13 { 14 map.get(nums[i])[1] = i; // update this num's end index 15 map.get(nums[i])[2]++; // update this num's occurrence 16 } 17 else // first time that store into map 18 { 19 int[] numInfo = new int[3]; 20 numInfo[0] = i; // store this num's begin index 21 numInfo[1] = i; // store this num's end index 22 numInfo[2] = 1; // store this num's occurrence 23 map.put(nums[i], numInfo); 24 } 25 26 maxFre = Math.max(maxFre, map.get(nums[i])[2]); // update maxFre 27 } 28 29 // second map keys iteration: find the minLen for numbers that have maxFre 30 for(int num: map.keySet()) 31 if(maxFre == map.get(num)[2]) 32 minLen = Math.min(minLen, map.get(num)[1] - map.get(num)[0] + 1); 33 34 35 return minLen; 36 } 37 }
參考資料:N/A
LeetCode 題目列表 - LeetCode Questions List