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

Guess you like

Origin blog.csdn.net/qq_45826803/article/details/121437431