659. 分割数组为连续子序列

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);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值