美文网首页
Split Array into Consecutive Sub

Split Array into Consecutive Sub

作者: Frank_Kivi | 来源:发表于2018-06-28 10:43 被阅读12次

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

    相关文章

      网友评论

          本文标题:Split Array into Consecutive Sub

          本文链接:https://www.haomeiwen.com/subject/zofgyftx.html