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

来源:互联网 发布:php删除相同前缀文件 编辑:程序博客网 时间:2024/05/18 02:07

算法作业系列(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: TrueExplanation:You can split them into two consecutive subsequences : 1, 2, 33, 4, 5

Example 2:

Input: [1,2,3,3,4,4,5,5]Output: TrueExplanation:You can split them into two consecutive subsequences : 1, 2, 3, 4, 53, 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
原创粉丝点击