一、题目粗心

https://leetcode.cn/problems/...

谐和数组是指一个数组里元素的最大值和最小值之间的差异 正好是 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 什么时候能水果自在呀