題目:
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.
顧名思義,找到陣列裡重複出現次數最多的數,把這個數最一開始出現到最後出現形成子陣列,回傳最小長度的子陣列即可。
範例
Input: nums = [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.
題目: 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. 顧名思義,找到陣列裡重複出現次數最多的數,把這個數最一開始出現到最後出現形成子陣列,回傳最小長度的子陣列即可。
範例
思路: 選擇用HashMap先去把陣列中每個數當key,該數出現的次數當value存起來,找出HashMap用value排序最大的數(亦即該陣列出現最多次處的數),然後去跑function findShortestDegree() ->找出該數的子陣列長度,回傳存進ArrayList(用ArrayList裝的用處是怕有多個重複次數一樣的數),最後排序ArrayList拿取最小的即為答案
解題: