64最长和谐子序列(594)

作者: Turbo时间限制: 1S章节: 哈希表

晚于: 2020-08-19 12:00:00后提交分数乘系数50%

截止日期: 2020-08-26 12:00:00

问题描述 :

和谐数组是指一个数组(长度>=2)里元素的最大值和最小值之间的差别正好是1。

现在,给定一个整数数组,你需要在所有可能的子序列中找到最长的和谐子序列的长度。

如果找不到这样的数组,则输出0。

 

示例 :

输入: [1,3,2,2,5,2,3,7]

输出: 5

原因: 最长的和谐数组是:[3,2,2,2,3].

说明: 输入的数组长度最大不超过20,000.

 

输入说明 :

首先输入整数数组的长度n,2<=n<=10000

然后输入n个整数,以空格分隔。

 

输出说明 :

输出最长的和谐子序列的长度

输入范例 :

输出范例 :

#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;

class Solution 
{
public:
    int findLHS(vector<int>& nums) 
    {
        int res=0;
        unordered_map<int,int> map;
        for(auto &i:nums) 
            map[i]++;
        for(auto &t:map)
        {
            //对于哈希表里面的每个键,查看是否存在(该键+1),如果存在,计算该和鞋子序列是否为最长的序列。 
            if(map.count(t.first+1))
                res=max(res,t.second+map[t.first+1]);//一定要和自己比较 
        }
        return res;
    }
};

int main()
{
    int n,data,k;
    vector<int> nums;
    cin>>n;
    for(int i=0; i<n; i++)
    {
        cin>>data;
        nums.push_back(data);
    }
    int res=Solution().findLHS(nums);
    cout<<res;
    return 0;
}

 

posted on 2020-09-09 17:31  Hi!Superman  阅读(227)  评论(0)    收藏  举报

导航