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

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

生活随笔

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

编程问答

leetcode 697 Degree of an Array

發(fā)布時(shí)間:2025/3/21 编程问答 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 leetcode 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.

輸入一個(gè)正整數(shù)數(shù)組,這個(gè)數(shù)組的“度”就是數(shù)組中任意元素出現(xiàn)的最大次數(shù)。而我們要找出這個(gè)數(shù)組的一個(gè)子數(shù)組,滿足“度”等于整個(gè)數(shù)組的“度”的同時(shí),保證子數(shù)組的長(zhǎng)度最小,返回這個(gè)最小的長(zhǎng)度。

Example 1:
Input: [1, 2, 2, 3, 1]
Output: 2
Explanation:
輸入數(shù)組的度為2(因?yàn)樵?和2都出現(xiàn)過(guò)兩次)
所有度為2的子數(shù)組:
[1, 2, 2, 3, 1], [1, 2, 2, 3], [2, 2, 3, 1], [1, 2, 2], [2, 2, 3], [2, 2]
最短的長(zhǎng)度為2,所以返回2。
Example 2:
Input: [1,2,2,3,1,4,2]
Output: 6

想法

  • 想盡量減少遍歷的次數(shù),因此在第一趟遍歷中我們即保存了所有元素出現(xiàn)的次數(shù),也保存了每個(gè)元素出現(xiàn)的范圍。
  • 因?yàn)樯婕暗綄?duì)元素出現(xiàn)次數(shù)的計(jì)數(shù),因此我們采用HashMap來(lái)實(shí)現(xiàn)。一個(gè)HashMap保存元素的值和出現(xiàn)的次數(shù)。另一個(gè)Hashmap保存元素的值和元素出現(xiàn)的范圍,用int[] numRange數(shù)組表示,numRange[0]表示第一次出現(xiàn)的位置,numRange[1]表示最后出現(xiàn)的位置。
  • 最后遍歷HashMap,獲取滿足“度”相等的最小子數(shù)組長(zhǎng)度。

解法

public int findShortestSubArray(int[] nums) {int minLength = nums.length;int degree = 0;HashMap<Integer, Integer> count = new HashMap<Integer,Integer>();HashMap<Integer,Integer[]> index = new HashMap<Integer,Integer[]>();for(int i=0;i<nums.length;i++){count.put(nums[i], count.getOrDefault(nums[i], 0) + 1);degree = Math.max(degree, count.get(nums[i]));if(index.get(nums[i]) == null){index.put(nums[i],new Integer[2]);}Integer[] numRange = index.get(nums[i]);if(numRange[0] == null)numRange[0] = i;numRange[1] = i;}for(Map.Entry<Integer, Integer> entry : count.entrySet()){if(entry.getValue() != degree){continue;}Integer[] range = index.get(entry.getKey());minLength = Math.min(minLength, range[1]-range[0]+1);}return minLength;}

總結(jié)

以上是生活随笔為你收集整理的leetcode 697 Degree of an Array的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

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