594. 最长和谐子序列

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

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

示例 1:

输入: [1,3,2,2,5,2,3,7]
输出: 5
原因: 最长的和谐数组是:[3,2,2,2,3].

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-harmonious-subsequence

 1 import java.util.HashMap;
 2 import java.util.Map;
 3 
 4 public class LhsFind {
 5     public int findLHS(int[] nums) {
 6         Map<Integer, Integer> map = new HashMap<>();
 7         for(int i = 0; i < nums.length; i++) {
 8             if(map.containsKey(nums[i])) {
 9                 int value = map.get(nums[i]) + 1;
10                 map.put(nums[i], value);
11             }else {
12                 map.put(nums[i], 1);
13             }
14         }
15         int res = 0;
16         for(Integer key : map.keySet()) {
17             if(map.containsKey(key + 1)) {
18                 int temp = map.get(key) + map.get(key + 1);
19                 res = Math.max(temp, res);
20             }
21         }
22         return res;
23     }
24 }
无论有多困难,都坚强的抬头挺胸,人生是一场醒悟,不要昨天,不要明天,只要今天。不一样的你我,不一样的心态,不一样的人生,顺其自然吧
原文地址:https://www.cnblogs.com/xiyangchen/p/11210931.html