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.

    解题思路:

    把数组出现最多的保存到一个数字,对每个数字找头尾最先出现的序列,与min_distance做比较。

    1. class Solution {  
    2. public:  
    3.     int findShortestSubArray(vector<int>& nums) {  
    4.         if(nums.size()==0) return 0;  
    5.         unordered_map<int,int> store;  
    6.         int max_digit=0;  
    7.         vector<int> digit;  
    8.         for(int i=0;i<nums.size();i++){  
    9.             store[nums[i]]++;  
    10.               
    11.             if(store[nums[i]]>max_digit) max_digit = store[nums[i]];  
    12.         }  
    13.         if(max_digit == 1) return 1;  
    14.         for(unordered_map<int,int>::iterator iter= store.begin();iter!=store.end();iter++){  
    15.             if((*iter).second == max_digit) digit.push_back((*iter).first);  
    16.         }  
    17.         int min_distance = 99999;  
    18.         for(int i=0;i<digit.size();i++){  
    19.             //找最小间距  
    20.             int index1=0;  
    21.             int index2=0;  
    22.             for(int j=0;j<nums.size();j++){        
    23.                if(nums[j] == digit[i]) {index1 =j;break;}  
    24.             }  
    25.             for(int j=nums.size()-1;j>=0;j--){        
    26.                if(nums[j] == digit[i]) {index2 =j;break;}  
    27.             }  
    28.             if(index2-index1<min_distance) min_distance=index2-index1;  
    29.               
    30.         }  
    31.         return min_distance+1;  
    32.           
    33.     }  
    34. };  
  • 相关阅读:
    Excel基础—文件菜单之创建保存
    Excel技巧—名称框的妙用
    Excel基础—文件菜单之设置信息
    Excel基础—文件菜单之打印共享账户
    Excel基础—文件菜单之设置选项
    Excel基础—工作界面概述
    linux环境下pathinfo 工作失败的改进函数
    javascript为网页元素绑定click事件
    将纯真ip数据库解析并导入mysql数据库中
    pgsql导入和导出数据
  • 原文地址:https://www.cnblogs.com/liangyc/p/8820479.html
Copyright © 2011-2022 走看看