594. 最長和諧子序列
和諧數組是指一個數組裏元素的最大值和最小值之間的差別正好是1。
現在,給定一個整數數組,你需要在所有可能的子序列中找到最長的和諧子序列的長度。
示例 1:
輸入: [1,3,2,2,5,2,3,7] 輸出: 5 原因: 最長的和諧數組是:[3,2,2,2,3].說明: 輸入的數組長度最大不超過20,000.
解法一
//時間複雜度O(nlogn), 空間複雜度O(1)
class Solution {
public:
int findLHS(vector<int>& nums) {
int n = nums.size(), res = 0, i = 0, j = 1, next = 0;
sort(nums.begin(), nums.end());
while(next < n) {
i = next;
while(j < n && nums[j] == nums[i]) j++;
next = j;
while(j < n && nums[j] - nums[i] == 1) j++;
if(j > next) res = max(res, j - i);
}
return res;
}
};
解法二
//時間複雜度O(n), 空間複雜度O(n)
class Solution {
public:
int findLHS(vector<int>& nums) {
unordered_map<int, int> um;
int res = 0;
for(int num : nums) ++um[num];
for(auto p = um.begin(); p != um.end(); p++) {
if(um.count(p->first + 1)) res = max(res, p->second + um[p->first + 1]);
}
return res;
}
};
思路:
解法一:
雙指針法。
- 先對數組由小到大排序,開始一次遍歷。
- 遍歷過程中,使用res記錄出現過的和諧子序列的最大長度,i指向和諧子序列的最小元素,j指向和諧子序列的最大元素的下一個位置,next指向下一個i要移動到的位置;
- 在一次循環體內,如果j == next,說明這個子序列最大值 - 最小值之差爲0(即這個子序列不是和諧子序列),此時不需要更新res;
- 當next (j)到達結尾時,返回res。
解法二:
使用一個哈希表unorder_map,記錄每個元素的值和出現的次數,然後遍歷哈希表,遍歷過程中向上查找大1的元素,(當前元素個數) + (當前元素 + 1的元素的個數)是潛在的最大值,若此值大於res,就更新res。