zoukankan      html  css  js  c++  java
  • leetcode-594-Longest Harmonious Subsequence

    题目描述:

    We define a harmonious array is an array where the difference between its maximum value and its minimum value is exactly 1.

    Now, given an integer array, you need to find the length of its longest harmonious subsequence among all its possible subsequences.

    Example 1:

    Input: [1,3,2,2,5,2,3,7]
    Output: 5
    Explanation: The longest harmonious subsequence is [3,2,2,2,3].
    

     

    Note: The length of the input array will not exceed 20,000.

     

    要完成的函数:

    int findLHS(vector<int>& nums)

     

    说明:

    最大值和最小值相差1,vector里面的数值又都是整数,所以我们要找的子数组只能包含最大值和最小值,不能有其他中间值。

    所以我们找1有几个,跟1相差1的(这里我们找同方向的数)即2,有多少个。2有几个,跟2相差1的(依然同个方向)即3,有多少个。

    最终统计完,我们就可以知道最长的子数组有多少个元素了。

    遍历一遍vector,我们可以用map来存储数值的个数。

    然后再遍历一遍map,按照上述方法统计各个子数组的长度,记录最长的长度。

    代码如下:

        int findLHS(vector<int>& nums) 
        {
            unordered_map<int,int>m1;//采用unordered_map更快
            for(int i=0;i<nums.size();i++)//存储各种数字的个数
            {
                if(!m1.count(nums[i]))
                    m1[nums[i]]=1;
                else
                    m1[nums[i]]++;
            }
            int max1=0;
            for(unordered_map<int,int>::iterator iter=m1.begin();iter!=m1.end();iter++)
            {
                if(m1.count(iter->first+1))//如果存在大1的数
                {
                    max1=max(max1,m1[iter->first+1]+iter->second);
                }
            }
            return max1;
        }

    上述代码简洁,实测93ms,beats 74.88% of cpp submissions。

    -----------------------------------------------------------------------------------

    最近在尝试分享文章到腾讯云+社区,两边都会更新的。

    我的博客即将搬运同步至腾讯云+社区,邀请大家一同入驻:https://cloud.tencent.com/developer/support-plan?invite_code=3n2y30g8cc6cs

  • 相关阅读:
    [Scoi2010]游戏
    HDU3415(单调队列)
    POJ1221(整数划分)
    POJ1050(dp)
    POJ2479(dp)
    HDU1864(背包)
    HDU1175(dfs)
    STL_string.vector中find到的iterator的序号
    Qt532.数值转为16进制(并填充)
    异常处理.VC++
  • 原文地址:https://www.cnblogs.com/chenjx85/p/8992609.html
Copyright © 2011-2022 走看看