package com.heu.wsq.leetcode;
import java.util.ArrayList;
import java.util.List;
/**
* 659. 分割数组为连续子序列
* @author wsq
* @date 2020/12/4
* 给你一个按升序排序的整数数组 num(可能包含重复数字),请你将它们分割成一个或多个子序列,其中每个子序列都由连续整数组成且长度至少为 3 。
* 如果可以完成上述分割,则返回 true ;否则,返回 false 。
*
* 示例 1:
* 输入: [1,2,3,3,4,5]
* 输出: True
* 解释:
* 你可以分割出这样两个连续子序列 :
* 1, 2, 3
* 3, 4, 5
*
* 示例 2:
* 输入: [1,2,3,3,4,4,5,5]
* 输出: True
* 解释:
* 你可以分割出这样两个连续子序列 :
* 1, 2, 3, 4, 5
* 3, 4, 5
*
* 链接:https://leetcode-cn.com/problems/split-array-into-consecutive-subsequences
*/
public class IsSubPossible {
/**
* 采用有序列表存储当前子序列的情况
* 列表中元素为数据类型int [2]
* 索引0:表示子序列的尾元素
* 索引1:表示该子序列的长度
*/
public boolean isPossible(int[] nums) {
List<Integer[]> tmpList = new ArrayList<>();
for (int num : nums) {
if(tmpList.size() == 0){
tmpList.add(new Integer[]{num, 1});
continue;
}
boolean flag = false;
for(int i = tmpList.size() -1; i >= 0; i--){
Integer[] arr = tmpList.get(i);
if(arr[0] == num){
continue;
}
if(arr[0] + 1 == num){
arr[0] = num;
arr[1]++;
flag = true;
break;
}
}
if (!flag){
tmpList.add(new Integer[]{num, 1});
}
}
for (Integer[] integers : tmpList) {
if (integers[1] < 3){
return false;
}
}
return true;
}
public static void main(String[] args) {
int[] arr = {1,2,3,4,4,5};
IsSubPossible sp = new IsSubPossible();
boolean possible = sp.isPossible(arr);
System.out.println(possible);
}
}