659. Split Array into Consecutive Subsequences
Question
You are given an integer array
nums
that is sorted in non-decreasing order.Determine if it is possible to split
nums
into one or more subsequences such that both of the following conditions are true:
- Each subsequence is a consecutive increasing sequence (i.e. each integer is exactly one more than the previous integer).
- All subsequences have a length of
3
** or more**.Return
true
* if you can splitnums
according to the above conditions, orfalse
otherwise*.A subsequence of an array is a new array that is formed from the original array by deleting some (can be none) of the elements without disturbing the relative positions of the remaining elements. (i.e.,
[1,3,5]
is a subsequence of[<u>1</u>,2,<u>3</u>,4,<u>5</u>]
while[1,3,2]
is not).
Solution
用优先级队列储存每个可组成的列表。
优先级队列根据列表的长度排列。
用哈希表记录每个列表的尾数,和其对应的优先级队列。
遍历所有数字,如果存在当前数字num-1为尾数的队列,则获取长度最小的列表,并添加当前数字num在列表中。
然后将新的优先级队列放入哈希表中。
遍历整个哈希表中的数组,如果有数组的长度小于3,则返回false,否则返回true。
Code
1 | class Solution { |
Solution 2
不需要保存整个列表,只需要保存对应末尾数字的列表长度即可。
Code
1 | class Solution { |
659. Split Array into Consecutive Subsequences
https://xuanhe95.github.io/2022/08/21/659-Split-Array-into-Consecutive-Subsequences/