leetcode 594. Longest Harmonious Subsequence 最长和谐子序列(简单).md

一、题目大意

https://leetcode.cn/problems/longest-harmonious-subsequence

和谐数组是指一个数组里元素的最大值和最小值之间的差别 正好是 1 。

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

数组的子序列是一个由数组派生出来的序列,它可以通过删除一些元素或不删除元素、且不改变其余元素的顺序而得到。

示例 1:

输入:nums = [1,3,2,2,5,2,3,7]
输出:5
解释:最长的和谐子序列是 [3,2,2,2,3]

示例 2:

输入:nums = [1,2,3,4]
输出:2

示例 3:

输入:nums = [1,1,1,1]
输出:0

提示:

  • 1 <= nums.length <= 2 * 104
  • -109 <= nums[i] <= 109

二、解题思路

思路:题目给我们一个数组,让我们找出最长的和谐子序列,和谐子序列就是序列中数组的最大最小差值均为1,这里只让我们求长度,而不需要返回具体的子序列。所以我们可以对数组进行排序,实际上只要找出来相差为1的两个数的总共出现个数就是一个和谐子序列长度了。

三、解题方法

3.1 Java实现

public class Solution {
    public int findLHS(int[] nums) {
        Map<Integer, Integer> countMap = new HashMap<>();
        for (int num : nums) {
            countMap.put(num, countMap.getOrDefault(num, 0) + 1);
        }

        // a-b由小到大 b-a由大到小
        PriorityQueue<Map.Entry<Integer, Integer>> priorityQueue
                = new PriorityQueue<>(Comparator.comparingInt(Map.Entry::getKey));
        for (Map.Entry<Integer, Integer> entry : countMap.entrySet()) {
            priorityQueue.add(entry);
        }

        int ans = 0;
        Map.Entry<Integer, Integer> pre = priorityQueue.poll();
        while (!priorityQueue.isEmpty()) {
            Map.Entry<Integer, Integer> cur = priorityQueue.poll();
            if (cur.getKey() - pre.getKey() == 1) {
                ans = Math.max(ans, cur.getValue() + pre.getValue());
            }
            pre = cur;
        }

        return ans;
    }
}

四、总结小记

  • 2022/8/24 什么时候能水果自由呀
posted @ 2022-08-24 23:35  okokabcd  阅读(57)  评论(0编辑  收藏  举报