ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

[Leetcode]659.Split Array into Consecutive Subsequences

2020-01-31 16:06:57  阅读:300  来源: 互联网

标签:count return nums int into 序列 Subsequences Split need


链接:LeetCode659

输入一个按升序排序的整数数组(可能包含重复数字),你需要将它们分割成几个子序列,其中每个子序列至少包含三个连续整数。返回你是否能做出这样的分割?

示例 1:

输入: \([1,2,3,3,4,5]\)
输出: True
解释:
你可以分割出这样两个连续子序列 :
1, 2, 3
3, 4, 5

相关标签:贪心

一般来说,贪心的题目是写起来最简单,想起来最难的。这里我们考虑是否能分割出多个连续子序列:在遍历构造连续子序列时,考虑一个数的位置,只有两种情况:要么加在之前的某个序列后面,要么自己新建一个子序列;如果都不行,则说明无法做出分割。
首先,我们将所有数存入哈希表count,其中键为数值,值为该数个数;在构建一个哈希表need,代表我们可以加入已知子序列后的数。那么我们在遍历每一个数n时,我们要分以下情况:

  • 当count[n]==0,说明该数已经被用完了,继续即可。
  • 当该数在need哈希表中,说明该数可以加入已知子序列中,则need[n]-=1;并且此时我们再加入该子序列时,则应该为n+1,所以need[n+1]+=1;
  • 当其上条件不满足,则需要重建一个子序列,那么当前仅当n+1和n+2存在时,才能新建一个子序列,否则返回False即可。
    代码如下:

python:

import collections
class Solution:
    def isPossible(self, nums: List[int]) -> bool:
        need = collections.defaultdict(int)
        count = collections.Counter(nums)
        for n in nums:
            if not count[n]:
                continue
            elif need[n]:
                need[n] -= 1
                need[n+1] += 1
            elif count[n+1]>0 and count[n+2]>0:
                count[n+1] -= 1
                count[n+2] -= 1
                need[n+3] +=1
            else:
                return False
            count[n] -=1
        return True

C++:

class Solution {
public:
    bool isPossible(vector<int>& nums) {
        map<int,int> count;
        map<int,int> need;
        for(int n:nums) count[n]++;
        for(int n:nums){
            if(count[n]==0){
                continue;
            }
            else if(need[n]>0){
                need[n]--;
                need[n+1]++;
            }
            else if (count[n+1]>0 && count[n+2]>0){
                count[n+1]--;
                count[n+2]--;
                need[n+3]++;
            }
            else{
                return false;
            }
            count[n] --;
        }
        return true;
    }
};

标签:count,return,nums,int,into,序列,Subsequences,Split,need
来源: https://www.cnblogs.com/hellojamest/p/12245640.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有