LeetCode # Array # Easy # 697 Degree of an Array

 

题意:给定一个数组,数组的度是其中出现最多次数的元素。求,最小连续子数组的度和原数组一致。

思路:(参考最佳答案)

遍历数组,找到数组最大值,然后根据最大值设置三个长度为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/

posted @ 2018-05-15 21:44  何以解忧,唯有撸代码  阅读(197)  评论(0编辑  收藏  举报