697. 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.

  • 给定一个非空数组的非负整数nums,该数组的“度”被定义为其任何一个元素的最大频率。 
    你的任务是找到num的子数组的最小可能长度,子数组与nums的“度”相同。
    1. /**
    2. * @param {number[]} nums
    3. * @return {number}
    4. */
    5. var findShortestSubArray = function(nums) {
    6. if (nums.length == 0 || !nums) {
    7. return 0;
    8. }
    9. let m = {};
    10. let maxTimes = 0;
    11. for (let i = 0; i < nums.length; i++) {
    12. let num = nums[i];
    13. let item = m[num];
    14. if (item) {
    15. item.right = i;
    16. item.times++;
    17. maxTimes = Math.max(item.times, maxTimes);
    18. } else {
    19. m[num] = {
    20. times: 1,
    21. left: i,
    22. right: i
    23. }
    24. maxTimes = Math.max(1, maxTimes);
    25. }
    26. }
    27. let min = 2147483647;
    28. for (let i in m) {
    29. let item = m[i];
    30. if (item.times == maxTimes) {
    31. if (item.left == item.right) {
    32. min = Math.min(1, min);
    33. } else {
    34. min = Math.min(item.right - item.left + 1, min);
    35. }
    36. }
    37. }
    38. return min;
    39. };





    posted @ 2017-10-15 21:55  xiejunzhao  阅读(175)  评论(0编辑  收藏  举报