其他分享
首页 > 其他分享> > 659. Split Array into Consecutive Subsequences

659. Split Array into Consecutive Subsequences

作者:互联网

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:

Return true if you can split nums according to the above conditions, or false 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 [1,2,3,4,5] while [1,3,2] is not).

 

Example 1:

Input: nums = [1,2,3,3,4,5]
Output: true
Explanation: nums can be split into the following subsequences:
[1,2,3,3,4,5] --> 1, 2, 3
[1,2,3,3,4,5] --> 3, 4, 5

Example 2:

Input: nums = [1,2,3,3,4,4,5,5]
Output: true
Explanation: nums can be split into the following subsequences:
[1,2,3,3,4,4,5,5] --> 1, 2, 3, 4, 5
[1,2,3,3,4,4,5,5] --> 3, 4, 5

Example 3:

Input: nums = [1,2,3,4,4,5]
Output: false
Explanation: It is impossible to split nums into consecutive increasing subsequences of length 3 or more.

 

Constraints:

class Solution {
    public boolean isPossible(int[] nums) {
        int n = nums.length;
        if(n < 3) return false;
        PriorityQueue<Interval> pq = new PriorityQueue<>((a, b) -> a.end == b.end ? a.len - b.len : a.end - b.end);
        for(int i : nums) {
            while(!pq.isEmpty() && (pq.peek().end + 1 < i)) {
                if(pq.poll().len < 3) return false;
            }
            if(pq.isEmpty() || i == pq.peek().end) {
                pq.add(new Interval(i, 1));
            }
            else {
                Interval it = pq.poll();
                it.len++;
                it.end = i;
                pq.add(it);
            }
        }
        
        while(!pq.isEmpty()) {
            if(pq.poll().len <3) return false;
        }
        return true;
    }
    
    class Interval {
        int end;
        int len;
        public Interval(int end, int len) {
            this.end = end;
            this.len = len;
        }
    }
}

https://leetcode.com/problems/split-array-into-consecutive-subsequences/discuss/130452/20ms-Java-PriorityQueue-with-Explanations

标签:pq,end,nums,into,Subsequences,Split,subsequences,split
来源: https://www.cnblogs.com/wentiliangkaihua/p/16601666.html