LeetCode594-最长和谐子序列

题目链接

英文链接:https://leetcode.com/problems/longest-harmonious-subsequence/

中文链接:https://leetcode-cn.com/problems/longest-harmonious-subsequence/

题目详述

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

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

示例 1:

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

说明: 输入的数组长度最大不超过20,000.

题目详解

  • 遍历数组,运用哈希表存储每个数出现的次数。
  • 接着遍历哈希表,判断是否存在差值为一的两个 key,取出对应的出现次数,相加然后更新结果。
  • 时间复杂度为 O(n)
  • 空间复杂度为 O(n)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class LeetCode_00594 {

public int findLHS(int[] nums) {
Map<Integer, Integer> map = new HashMap<>();
for (int num : nums) {
map.put(num, map.getOrDefault(num, 0) + 1);
}
int res = 0;
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
if (map.containsKey(entry.getKey() + 1)) {
res = Math.max(res, entry.getValue() + map.get(entry.getKey() + 1));
}
}
return res;
}
}
  • 对数组进行排序,再进行统计。
  • 时间复杂度为 O(nlogn)
  • 空间复杂度为 O(logn)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public class LeetCode_00594 {

public int findLHS(int[] nums) {
Arrays.sort(nums);
int res = 0;
int preCount = 0;
for (int i = 0; i < nums.length; ++i) {
int count = 1;
if (i > 0 && nums[i] - nums[i - 1] == 1) {
while (i + 1 < nums.length && nums[i + 1] == nums[i]) {
++count;
++i;
}
res = Math.max(res, preCount + count);
} else {
while (i + 1 < nums.length && nums[i + 1] == nums[i]) {
++count;
++i;
}
}
preCount = count;
}
return res;
}
}