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.
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?[暴力解法]:
時(shí)間分析:
空間分析:
?[優(yōu)化后]:
時(shí)間分析:
空間分析:
[奇葩輸出條件]:
[奇葩corner case]:
[思維問(wèn)題]:
讀題不懂
[一句話思路]:
先統(tǒng)計(jì),再比較
[輸入量]:空:?正常情況:特大:特小:程序里處理到的特殊情況:異常情況(不合法不合理的輸入):
[畫(huà)圖]:
[一刷]:
[二刷]:
[三刷]:
[四刷]:
[五刷]:
? [五分鐘肉眼debug的結(jié)果]:
[總結(jié)]:
有很多指標(biāo),所以用多維數(shù)組+hashmap來(lái)實(shí)現(xiàn)
[復(fù)雜度]:Time complexity: O(n) Space complexity: O(n)
[英文數(shù)據(jù)結(jié)構(gòu)或算法,為什么不用別的數(shù)據(jù)結(jié)構(gòu)或算法]:
[關(guān)鍵模板化代碼]:
[其他解法]:
[Follow Up]:
[LC給出的題目變變變]:
?[代碼風(fēng)格] :
put中直接寫數(shù)值 不能再賦值,所以new int[]{直接跟數(shù)組即可}
class Solution {public int findShortestSubArray(int[] nums) {//ccif (nums == null || nums.length == 0) {return 0;}//iniHashMap<Integer, int[]> map = new HashMap<>();//collect into hashmapfor (int i = 0; i < nums.length; i++) {if (!map.containsKey(nums[i])) {map.put(nums[i], new int[]{1, i, i});//val, first index, last index}else {int temp[] = map.get(nums[i]);temp[0] += 1;temp[2] = i;map.put(nums[i], temp);}}//compare//bigger degree//same degree but smaller range//ini to the extremeint degree = Integer.MIN_VALUE;int result = Integer.MAX_VALUE;for (int[] val : map.values()) {if (val[0] > degree) {degree = val[0];result = val[2] - val[1] + 1;}else {if (val[0] == degree) {result = Math.min(result, val[2] - val[1] + 1);}}}//returnreturn result;} } View Code?
轉(zhuǎn)載于:https://www.cnblogs.com/immiao0319/p/8875741.html
總結(jié)
以上是生活随笔為你收集整理的697. Degree of an Array 频率最高元素的最小覆盖子数组的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: JAVA面向对象的特征
- 下一篇: 进程的创建模型