697. 陣列的度
阿新 • • 發佈:2019-01-12
給定一個非空且只包含非負數的整數陣列 nums
, 陣列的度的定義是指數組裡任一元素出現頻數的最大值。
你的任務是找到與 nums
擁有相同大小的度的最短連續子陣列,返回其長度。
示例 1:
輸入: [1, 2, 2, 3, 1] 輸出: 2 解釋: 輸入陣列的度是2,因為元素1和2的出現頻數最大,均為2. 連續子數組裡面擁有相同度的有如下所示: [1, 2, 2, 3, 1], [1, 2, 2, 3], [2, 2, 3, 1], [1, 2, 2], [2, 2, 3], [2, 2] 最短連續子陣列[2, 2]的長度為2,所以返回2.
示例 2:
輸入: [1,2,2,3,1,4,2] 輸出: 6
class Solution { public int findShortestSubArray(int[] nums) { HashMap<Integer,Integer> tj = new HashMap<>(); for(int i : nums){ int num = 0; if(tj.containsKey(i)) { num = tj.get(i); } num +=1; tj.put(i,num); } int max = 0; int maxNum = 0; for(int i : nums){ if(tj.get(i)>=max){ max = tj.get(i); maxNum = i; } } System.out.println(max); Set<Integer> set = tj.keySet(); int minDis = Integer.MAX_VALUE; for(int n:set){ int temp = Integer.MAX_VALUE; if(tj.get(n) == max){ int i=0,j = nums.length-1; while(nums[i] != n && i<j) i++; while(nums[j] != n && i<j) j--; temp = j - i + 1; } minDis = Math.min(temp,minDis); } return minDis; } }