594. Longest Harmonious Subsequence - LeetCode
Posted okokabcd
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了594. Longest Harmonious Subsequence - LeetCode相关的知识,希望对你有一定的参考价值。
Question
594. Longest Harmonious Subsequence
Solution
题目大意:找一个最长子序列,要求子序列中最大值和最小值的差是1。
思路:构造一个map,保存每个元素出现的个数,再遍历这个map,算出每个元素与其邻元素出现的次数和,并找到最大的那个数
Java实现:
public int findLHS(int[] nums) {
if (nums == null || nums.length == 0) return 0;
Map<Integer, Integer> map = new HashMap<>();
for (int tmp : nums) {
Integer cnt = map.get(tmp);
if (cnt == null) cnt = 0;
map.put(tmp, cnt + 1);
}
int count = 0;
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
int before = map.get(entry.getKey() - 1) != null ? map.get(entry.getKey() - 1) : -entry.getValue();
int next = map.get(entry.getKey() + 1) != null ? map.get(entry.getKey() + 1) : -entry.getValue();
if (before + entry.getValue() > count) count = before + entry.getValue();
if (next + entry.getValue() > count) count = next + entry.getValue();
}
return count;
}
以上是关于594. Longest Harmonious Subsequence - LeetCode的主要内容,如果未能解决你的问题,请参考以下文章
[leetcode-594-Longest Harmonious Subsequence]
leetcode 594. Longest Harmonious Subsequence
LeetCode 594. Longest Harmonious Subsequence
leetcode-594-Longest Harmonious Subsequence