zoukankan      html  css  js  c++  java
  • leetcode 之 Degree of an Array

    1、题目描述

    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.

    题目是说给定一个非空数组,找出其中出现最多的元素(不只一个),然后返回数组中包含出现最多的元素的最小子数组的长度。

    2、题目分析

    首先使用hash表统计每个元素的出现次数,然后找出每个出现最多的元素放入一个vector中,对vector中每个元素进行统计,找出包含vector中每个元素的最小子数组。

    3、代码

     1 int findShortestSubArray(vector<int>& nums) {
     2         
     3         unordered_map<int ,int> m;   // 将数组中所有元素放入一个hash_table 中
     4         vector<int> maxItem(0);
     5         int maxindex = 0;
     6         for( auto n : nums )
     7             m[n]++;
     8         
     9         
    10         for(auto itr = m.begin(); itr != m.end() ; itr++ )  // 找出出现次数最多的元素,放在一个vector中
    11             if(itr->second > maxindex )
    12             {
    13                 maxItem.clear();
    14                 maxItem.push_back(itr->first);
    15                 maxindex = itr->second;
    16             }
    17             else if( itr->second == maxindex )
    18             {
    19                 maxItem.push_back(itr->first);
    20             }
    21       
    22         
    23         int i=0,j= nums.size()-1;     // 对每个出现次数最多的元素进行检查,找出“度”最小的。
    24         int ans=nums.size();
    25         
    26         for(auto itr = maxItem.begin(); itr != maxItem.end(); itr++)
    27         {
    28             i = 0;j = nums.size()-1;
    29             while( nums[i] != *itr ) i++;
    30             while(nums[j] != *itr ) j--;
    31             ans = min(ans,j-i+1);
    32         }
    33        
    34         return ans;
    35     
    36     }
    pp
  • 相关阅读:
    去过的论坛重新注册了
    for … in … 语句的使用
    删除整个目录
    使用Live Writer测试 1
    Google ProtocolBuffer.net简介与使用
    linq to sql 系列之 linq to sql性能优化技巧
    单元测试之道(使用NUnit)
    提高软件测试能力的19条建议
    System.Runtime.Caching;
    EneityFramework+DomainDataSource+Silverlight完成数据读取分页排序与修改
  • 原文地址:https://www.cnblogs.com/wangxiaoyong/p/8744436.html
Copyright © 2011-2022 走看看