【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 。
解题方法
- 把子序列存到一个 list 列表里面
- 每次存进去的时候,从后往前遍历,遇到最后一个元素刚好等于当前元素 -1,就插入
- 如果比当前元素-1还小,直接remove,然后判断是否 size() 是否大于等于 3,方便以后再也不用判断
- 如果没找到就重新开一个子序列存到 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用户
![](https://img-blog.csdnimg.cn/20201107174624800.jpg?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzE2OTI3ODUz,size_16,color_FFFFFF,t_70#pic_center)