题目
类型:HashTable
解题思路
用一个哈希映射来存储每个数出现的次数,这样就能在 O(1) 的时间内得到 x 和 x + 1 出现的次数。
首先遍历一遍数组,得到哈希映射。
随后遍历哈希映射,设当前遍历到的键值对为 (x,value),那么查询 x+1 在哈希映射中对应的统计次数,就得到了 x 和 x+1 出现的次数,和谐子序列的长度等于 x 和 x + 1 出现的次数之和。
代码
class Solution {
public int findLHS(int[] nums) {
HashMap <Integer, Integer> cnt = new HashMap <>();
int res = 0;
for (int num : nums) {
cnt.put(num, cnt.getOrDefault(num, 0) + 1);
}
for (int key : cnt.keySet()) {
if (cnt.containsKey(key + 1)) {
res = Math.max(res, cnt.get(key) + cnt.get(key + 1));
}
}
return res;
}
}