leetcode 594. 最长和谐子序列
大约 1 分钟
和谐数组是指一个数组里元素的最大值和最小值之间的差别 正好是 1
。
现在,给你一个整数数组 nums
,请你在所有可能的子序列中找到最长的和谐子序列的长度。
数组的子序列是一个由数组派生出来的序列,它可以通过删除一些元素或不删除元素、且不改变其余元素的顺序而得到。
示例 1:
输入:nums = [1,3,2,2,5,2,3,7]
输出:5
解释:最长的和谐子序列是 [3,2,2,2,3]
方法一:哈希表
class Solution {
public:
int findLHS(vector<int>& nums) {
unordered_map<int,int> hashMap;
for(auto n : nums) { //记录元素出现的次数
hashMap[n]++;
}
int res = 0;
for(auto [key, value] : hashMap) {
if(hashMap.count(key + 1)) {
res = max(res, value + hashMap[key + 1]);
}
}
/*另一种写法 1.使用pair接收 2.find查找和count查找
for(const auto& p : hashMap){ //用p来接收hashMap的值(是pair)
if(visited.find(p.first+1) != visited.end()) { //能找到p.first+1的值
res = max(res, p.second+visited[p.first+1]);
}
}
*/
return res;
}
};
方法二:排序 + 双指针
class Solution {
public:
int findLHS(vector<int>& nums) {
sort(nums.begin(), nums.end());
int begin = 0;
int res = 0;
for(int end = 0; end < nums.size(); end++) {
while(nums[end] - nums[begin] > 1) {
++begin;
}
if(nums[end] - nums[begin] == 1) {
res = max(res, end - begin + 1);
}
}
return res;
}
};