zoukankan      html  css  js  c++  java
  • 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. };



来自为知笔记(Wiz)


查看全文
  • 相关阅读:
    Educational Codeforces Round 88 (Rated for Div. 2) D. Yet Another Yet Another Task(枚举/最大连续子序列)
    Educational Codeforces Round 88 (Rated for Div. 2) A. Berland Poker(数学)
    Educational Codeforces Round 88 (Rated for Div. 2) E. Modular Stability(数论)
    Educational Codeforces Round 88 (Rated for Div. 2) C. Mixing Water(数学/二分)
    Codeforces Round #644 (Div. 3)
    Educational Codeforces Round 76 (Rated for Div. 2)
    Educational Codeforces Round 77 (Rated for Div. 2)
    Educational Codeforces Round 87 (Rated for Div. 2)
    AtCoder Beginner Contest 168
    Codeforces Round #643 (Div. 2)
  • 原文地址:https://www.cnblogs.com/xiejunzhao/p/7674473.html
  • Copyright © 2011-2022 走看看