leetcode 697 Degree of an Array
生活随笔
收集整理的這篇文章主要介紹了
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.
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)題。
- 上一篇: 酷狗音乐在线试听下载
- 下一篇: WEBSERVICE之JDK开发webs