Degree of an Array

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: 
The input array has a degree of 2 because both elements 1 and 2 appear twice.
Of the subarrays that have the same degree:
[1, 2, 2, 3, 1], [1, 2, 2, 3], [2, 2, 3, 1], [1, 2, 2], [2, 2, 3], [2, 2]
The shortest length is 2. So return 2.

 

Example 2:

Input: [1,2,2,3,1,4,2]
Output: 6

 

Note:

  • nums.length will be between 1 and 50,000.
  • nums[i] will be an integer between 0 and 49,999.

 

 1 class Solution {
 2     public int findShortestSubArray(int[] nums) {
 3         // maps number with [count, startIndex, endIndex]
 4         HashMap<Integer, int[]> map = new HashMap<Integer, int[]>();
 5         
 6         int result = Integer.MAX_VALUE, maxCount = 0;
 7         for (int i = 0; i < nums.length; i++) {
 8             int[] numData = new int[3];
 9             if (map.containsKey(nums[i])) {
10                 int[] temp = map.get(nums[i]);
11                 numData[0] = temp[0] + 1;
12                 numData[1] = temp[1];
13             } else {
14                 numData[0] = 1;
15                 numData[1] = i;
16             }
17             numData[2] = i;
18             map.put(nums[i], numData);
19                 
20             if (numData[0] > maxCount) {
21                 maxCount = numData[0];
22                 result = numData[2] - numData[1] + 1;
23             } else if (numData[0] == maxCount) {
24                 result = Math.min(result, numData[2] - numData[1] + 1);
25             }
26         }
27         
28         return result;
29     }
30 }

 

posted @ 2018-05-24 12:17  amazingzoe  阅读(81)  评论(0编辑  收藏  举报