Split Array into Consecutive Sub

2018-06-28  本文已影响12人  Frank_Kivi

https://www.lintcode.com/problem/split-array-into-consecutive-subsequences/description

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;

public class Solution {
    /**
     * @param nums: a list of integers
     * @return: return a boolean
     */
    public boolean isPossible(int[] nums) {
        // write your code here
        List<LinkedList<Integer>> list = new ArrayList<>();
        Arrays.sort(nums);
        test:
        for (int i = 0; i < nums.length; i++) {
            int num = nums[i];
            Collections.sort(list, new Comparator<LinkedList<Integer>>() {
                @Override
                public int compare(LinkedList<Integer> o1, LinkedList<Integer> o2) {
                    return o1.size() - o2.size();
                }
            });
            for (int j = 0; j < list.size(); j++) {
                LinkedList<Integer> integers = list.get(j);
                if (num == integers.getLast() + 1) {
                    integers.add(num);
                    continue test;
                }
            }
            LinkedList linkedList = new LinkedList();
            linkedList.add(num);
            list.add(linkedList);
        }
        for (int i = 0; i < list.size(); i++) {
            LinkedList<Integer> integers = list.get(i);
            if (integers.size() < 3) {
                return false;
            }
        }
        return true;
    }
}
上一篇下一篇

猜你喜欢

热点阅读