日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程资源 > 编程问答 >内容正文

编程问答

697. Degree of an Array 频率最高元素的最小覆盖子数组

發(fā)布時(shí)間:2025/7/25 编程问答 26 豆豆
生活随笔 收集整理的這篇文章主要介紹了 697. Degree of an Array 频率最高元素的最小覆盖子数组 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

[抄題]:

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à)圖]:

[一刷]:

  • 數(shù)字一般初始化為整數(shù)中相反的最大或者最小值,忘了
  • 忘了 檢查key用的是containsKey方法
  • [二刷]:

    [三刷]:

    [四刷]:

    [五刷]:

    ? [五分鐘肉眼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)或算法]:

  • 某數(shù)字 最大值的 最小覆蓋范圍, 有很多指標(biāo),所以用多維數(shù)組+hashmap來(lái)實(shí)現(xiàn)
  • hashmap可以用for(: .values())冒號(hào)表達(dá)式把所有值取出來(lái)
  • [關(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)題。

    如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。