659. 分割数组为连续子序列
时间:2020年12月4日
知识点:贪心、哈希表
题目链接:https://leetcode-cn.com/problems/split-array-into-consecutive-subsequences/
题目
给你一个按升序排序的整数数组 num(可能包含重复数字),请你将它们分割成一个或多个子序列,其中每个子序列都由连续整数组成且长度至少为 3 。
如果可以完成上述分割,则返回 true ;否则,返回 false 。
示例 1:
输入: [1,2,3,3,4,5]
输出: True
解释:
你可以分割出这样两个连续子序列 :
1, 2, 3
3, 4, 5
示例 2:
输入: [1,2,3,3,4,4,5,5]
输出: True
解释:
你可以分割出这样两个连续子序列 :
1, 2, 3, 4, 5
3, 4, 5
示例 3:
输入: [1,2,3,4,4,5]
输出: False
提示:
- 输入的数组长度范围为 [1, 10000]
解法:
哈希表+最小堆
- 加入一个子序列我们需要知道 这个子序列的两个情况:1.子序列的末尾是什么 2.以数字x为结尾的子序列有多少个
- 我们可以用哈希表的键 来存储子序列的末尾是多少
- 哈希表对应的值 可以用最小堆 表示以这个数结尾的子序列有多少个
- 遍历nums中的数 如果以该数为最后一个的子序列不存在 先创建一个
- 找该数-1的为最后二个的子序列 是否存在 如果存在 加入现在个数最少的那个 这里由最小堆维护 注意堆里值的改变
- 否则 这个数为新的子序列,子序列的个数为1
哈希表+贪心
- 重点还是和第一个方法 一样 子序列的末尾是什么 以数字x为结尾的子序列有多少个
- 这里用两个哈希表 一个键是数值 值是数值出现的次数
- 还有一个 键是数值 值是以这个数结尾的子序列有多少个
- 遍历数组 只有 数值出现次数>0 才需要判断
- 如果 找的到以x-1结尾的子序列 x-1结尾的子序列个数减1 x结尾的个数加1
- 否则 找是否有x+1、x+2 和x能构成满足条件的最少3个子序列 没有返回false 否则 以x+2结尾的子序列加1
代码
#include <stdio.h>
#include <iostream>
#include <vector>
#include <unordered_map>
#include <queue>
using namespace std;
/*
class Solution {
public:
bool isPossible(vector<int>& nums) {
unordered_map<int, priority_queue<int,vector<int>,greater<int> >> mp;
for(int x : nums){
if(mp.find(x) == mp.end())
mp[x] = priority_queue<int,vector<int>,greater<int>>();
if(mp.find(x-1) != mp.end()){
int prelength = mp[x-1].top();
mp[x-1].pop();
mp[x].push(prelength+1);
if(mp[x-1].empty())
mp.erase(x-1);
}else
mp[x].push(1);
}
for(auto it = mp.begin();it != mp.end(); it++)
{
priority_queue<int, vector<int>,greater<int>> tmp = it->second;
if (tmp.top() < 3) {
return false;
}
}
return true;
}
};
*/
class Solution {
public:
bool isPossible(vector<int>& nums) {
unordered_map<int, int> count_mp, end_mp;
for(int x : nums)
count_mp[x]++;
for(int x:nums){
if(count_mp[x] == 0) continue;
if(end_mp[x-1]){
end_mp[x-1]--;
end_mp[x]++;
count_mp[x]--;
}else if(count_mp[x+1] && count_mp[x+2]){
end_mp[x+2]++;
count_mp[x]--;count_mp[x+1]--;count_mp[x+2]--;
}
else
return false;
}
return true;
}
};
int main()
{
Solution s;
vector<int> nums{1,2,3,3,4,4,5,5};
cout<<s.isPossible(nums)<<endl;
return 0;
}
今天也是爱zz的一天哦!