算法作业系列9——Split Array into Consecutive Subsequences

算法作业系列(9)

Split Array into Consecutive Subsequences

题目

You are given an integer array sorted in ascending order (may contain duplicates), you need to split them into several subsequences, where each subsequences consist of at least 3 consecutive integers. Return whether you can make such a split.

Example 1:

Input: [1,2,3,3,4,5]
Output: True
Explanation:
You can split them into two consecutive subsequences : 
1, 2, 3
3, 4, 5

Example 2:

Input: [1,2,3,3,4,4,5,5]
Output: True
Explanation:
You can split them into two consecutive subsequences : 
1, 2, 3, 4, 5
3, 4, 5

Example 3:

Input: [1,2,3,4,4,5]
Output: False

Note:
The length of the input is in range of [1, 10000]

参考链接

别人的博客

思路分析

这道题是在贪心算法的专栏里,由于近期写动态规划的题目较多,所以对贪心不是很懂,这个也是查了别人的博客才理清楚。
其实原来的想法是有两个,一个就是尽可能去构建数字串,然后对每个长度不够的尝试去长的串上面进行切割,如果没有可以给他切割的,就返回false;另外一个想法是构建尽可能短的串,3个就够了,再对每个不够长的串进行拼接,最后看有没有不够长的就好。但是苦于实现难度,便想着找找看有没有其他的方法,这里的难度主要就在于vector的erase函数之后的指针问题。
那么接下来的就很好解决了,我们一样去构建串,将所有构建的串存入一个数组中,对于每一个数,遍历数组,如果数组为空,就以这个数为开头新建一个串;如果正好有一个可以让当前数加到结尾且长度小于3的串,那就毫不犹豫加上去;如果所有可以加到结尾的串长度都大于等于3,那就加到第一个满足的串最后;最后一种就是不存在可以加到结尾的了,那就重新建立一个串,放到数组最后。完成操作后,遍历看看有没有不够长的就好。

代码

#include<vector>
#include<iostream>
using namespace std;

class Solution {
public:
    bool isPossible(vector<int>& nums) {
        vector<vector<int> > set;
        for (int i = 0; i < nums.size(); i++) {
            int first = -1;
            bool flag = false;
            for (int j = 0; j < set.size(); j++) {
                if (set[j].size() < 3 && set[j][set[j].size() - 1] + 1 < nums[i]) {
                    return false;
                }
                if (set[j].size() < 3 && set[j][set[j].size() - 1] + 1 == nums[i]) {
                    set[j].push_back(nums[i]);
                    first = -1;
                    flag = true;
                    break;
                }
                if (set[j].size() >= 3 && set[j][set[j].size() - 1] + 1 == nums[i] && first == -1) {
                    first = j;
                }
            }

            if (first != -1) {
                set[first].push_back(nums[i]);
                continue;
            }
            if (flag == false) {
                vector<int> tmp({nums[i]});
                set.push_back(tmp);
            }
        }

        for (int i = 0; i < set.size(); i++) {
            if (set[i].size() <= 2) {
                return false;
            }
        }
        return true;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值