本文主要是介绍[LeetCode] 594. Longest Harmonious Subsequence,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题:https://leetcode.com/problems/longest-harmonious-subsequence/description/
题目
We define a harmonious array is an array where the difference between its maximum value and its minimum value is exactly 1.
Now, given an integer array, you need to find the length of its longest harmonious subsequence among all its possible subsequences.
Example 1:
Input: [1,3,2,2,5,2,3,7]
Output: 5
Explanation: The longest harmonious subsequence is [3,2,2,2,3].
Note: The length of the input array will not exceed 20,000.
题目大意
求最长的和谐序列,和谐序列中最大数和最小数只差正好为 1,应该注意的是序列的元素不一定是数组的连续元素。
思路
把每个元素的存入 map中。
map 中 key为元素,value 为元素的出现次数。
遍历每个map中的元素num,若num+1也在map中。
res = Math.max(map.get(num),map.get(num+1))
class Solution {public int findLHS(int[] nums) {Map<Integer,Integer> map = new HashMap<>();for(int num:nums)map.put(num,map.getOrDefault(num,0)+1);int max = 0;for(int num:map.keySet())if(map.containsKey(num+1)){max = Math.max(max,map.get(num)+map.get(num+1));}return max;}
}
这篇关于[LeetCode] 594. Longest Harmonious Subsequence的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!