1. 程式人生 > >LeetCode # Array # Easy # 697 Degree of an Array

LeetCode # Array # Easy # 697 Degree of an Array

pre array sub 次數 etc gre leet miss iss

題意:給定一個數組,數組的度是其中出現最多次數的元素。求,最小連續子數組的度和原數組一致。

思路:(參考最佳答案)

遍歷數組,找到數組最大值,然後根據最大值設置三個長度為max+1的數組left[],right[],counts[],分別用於存儲一個數第一次出現的索引、最後一次出現的索引、出現次數。然後,根據counts找到數組的度,再根據right-left求出最小的子數組長度。

 1 public class Solution {
 2     public int findShortestSubArray(int[] nums) {
 3         if(nums.length == 0 || nums == null
) return 0; 4 int max = 0,n=nums.length; 5 for(int num : nums){//求出最大值 6 max=Math.max(max, num); 7 } 8 int[] counts = new int[max+1]; 9 int[] left = new int[max+1]; 10 int[] right = new int[max+1]; 11 for(int i =0; i<n;i++){
12 if(counts[nums[i]] == 0){ 13 left[nums[i]] = i; 14 right[nums[i]] = i; 15 }else { 16 right[nums[i]] = i; 17 } 18 counts[nums[i]]++; 19 } 20 int max_count =0; 21 for(int count : counts){//求出數組的度
22 max_count = Math.max(max_count, count); 23 } 24 int min = max+1; 25 for(int i=0;i<max+1 ; i++){//求出最小長度 26 if(counts[i] == max_count) { 27 min = Math.min(min, right[i]-left[i]+1); 28 } 29 } 30 return min; 31 } 32 }

參考:https://leetcode.com/submissions/detail/154332786/

LeetCode # Array # Easy # 697 Degree of an Array