zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    chapter16 计算机体系结构基础
    ASP.NET 2.0加密Web.config 配置文件
    用IIS6.0的Kernel Caching 压缩技术提高应用程序性能
    .net中怎样执行一个字符串
    ASP.NET 页面生存周期中的关键事件
    ASP.NET获取客户端IP及MAC地址
    DOS命令关闭计算机
    1个式子检测密码强度
    徐州话六级考试
    .net2.0中新增的Substitution控件
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/9082244.html
Copyright © 2011-2022 走看看