leetcode每日一题-594:最长和谐子序列

leetcode每日一题-594:最长和谐子序列

链接

最长和谐子序列

题目

在这里插入图片描述



分析

因为最大值和最小值差值为1,那么这个序列中就只能存在两种类型的数字。遍历数组每次以当前值为最小值,查询当前值加1的值的数量是多少,两种类型的数字之和就是一个和谐序列的长度。那么我们如何快速获得x+1的数量呢,我们可以先用哈希表存储每中类型数字的数量,然后直接获取即可。



代码

C++

class Solution {
public:
    int findLHS(vector<int>& nums) {
        int n = nums.size(), res = 0;
        unordered_map<int, int> m;
        for(int x : nums) m[x]++;
        for(auto [key, val] : m)
        {
            // 先判断key+1是否存在,如果存在就更新一下res的值
            if(m.count(key + 1)) res = max(res, val + m[key + 1]);
        }
        return res;
    }
};

Java

class Solution {
    public int findLHS(int[] nums) {
        HashMap <Integer, Integer> cnt = new HashMap <>();
        int res = 0;
        for (int num : nums) {
            cnt.put(num, cnt.getOrDefault(num, 0) + 1);
        }
        for (int key : cnt.keySet()) {
            if (cnt.containsKey(key + 1)) {
                res = Math.max(res, cnt.get(key) + cnt.get(key + 1));
            }
        }
        return res;
    }
}

作者:LeetCode-Solution
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值