【LeetCode】659. Split Array into Consecutive Subsequences 分割数组为连续子序列(Medium)(JAVA)

【LeetCode】659. Split Array into Consecutive Subsequences 分割数组为连续子序列(Medium)(JAVA)

题目地址: https://leetcode.com/problems/split-array-into-consecutive-subsequences/

题目描述:

Given an array nums sorted in ascending order, return true if and only if you can split it into 1 or more subsequences such that each subsequence consists of consecutive integers and has length at least 3.

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

Constraints:

  • 1 <= nums.length <= 10000

题目大意

给你一个按升序排序的整数数组 num(可能包含重复数字),请你将它们分割成一个或多个子序列,其中每个子序列都由连续整数组成且长度至少为 3 。

如果可以完成上述分割,则返回 true ;否则,返回 false 。

解题方法

  1. 把子序列存到一个 list 列表里面
  2. 每次存进去的时候,从后往前遍历,遇到最后一个元素刚好等于当前元素 -1,就插入
  3. 如果比当前元素-1还小,直接remove,然后判断是否 size() 是否大于等于 3,方便以后再也不用判断
  4. 如果没找到就重新开一个子序列存到 list 列表里面
class Solution {
    public boolean isPossible(int[] nums) {
        if (nums.length < 3) return false;
        List<List<Integer>> list = new ArrayList<>();
        for (int i = 0; i < nums.length; i++) {
            List<Integer> cur;
            if (list.size() == 0) {
                cur = new ArrayList<>();
                cur.add(nums[i]);
                list.add(cur);
            } else {
                boolean flag = false;
                for (int j = list.size() - 1; j >= 0; j--) {
                    List<Integer> temp = list.get(j);
                    Integer last = temp.get(temp.size() - 1);
                    if (last == nums[i]) {
                        
                    } else if (last == nums[i] - 1) {
                        if (!flag) temp.add(nums[i]);
                        flag = true;
                    } else if (temp.size() >= 3) {
                        list.remove(j);
                    } else {
                        return false;
                    }
                }
                if (!flag) {
                    cur = new ArrayList<>();
                    cur.add(nums[i]);
                    list.add(cur); 
                }
            }
        }
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).size() < 3) return false;
        }
        return true;
    }
}

执行耗时:30 ms,击败了64.98% 的Java用户
内存消耗:39.3 MB,击败了87.76% 的Java用户

欢迎关注我的公众号,LeetCode 每日一题更新
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值