[LeetCode]Split Array into Consecutive Subsequences

题目描述:

LeetCode 659. Split Array into Consecutive Subsequences

You are given an integer array sorted in ascending order (may contain duplicates), you need to split them into several subsequences, where each subsequences consist of at least 3 consecutive integers. Return whether you can make such a split.

Example 1:

Input: [1,2,3,3,4,5]
Output: True
Explanation:
You can split them into two consecutive subsequences : 
1, 2, 3
3, 4, 5

Example 2:

Input: [1,2,3,3,4,4,5,5]
Output: True
Explanation:
You can split them into two consecutive subsequences : 
1, 2, 3, 4, 5
3, 4, 5

Example 3:

Input: [1,2,3,4,4,5]
Output: False

Note:

  1. The length of the input is in range of [1, 10000]

题目大意:

给定一个排好序的整数数组(可能包含重复),将其分隔成若干子数组,每个数组包含至少3个连续整数。判断是否可以做这样的划分。

解题思路:

Map + PriorityQueue

思路类似于排列扑克牌,优先将数字排在长度较小的扑克牌队列后面

Map<Integer, PriorityQueue<Integer>> dmap的key为扑克牌队列的末尾,value为优先队列,存储扑克牌队列的长度

Java代码:

public class Solution {
    private HashMap<Integer, PriorityQueue<Integer>> dmap;
    public boolean isPossible(int[] nums) {
        dmap = new HashMap<>();
        for (int num : nums) {
            PriorityQueue<Integer> pq0 = getOrPut(num - 1);
            int len = pq0.isEmpty() ? 0 : pq0.poll();
            PriorityQueue<Integer> pq1 = getOrPut(num);
            pq1.offer(len + 1);
        }
        for (int key : dmap.keySet()) {
            for (int len : dmap.get(key)) {
                if (len < 3) return false;
            }
        }
        return true;
    }
    public PriorityQueue<Integer> getOrPut(int num) {
        PriorityQueue<Integer> pq = dmap.get(num);
        if (pq == null) {
            pq = new PriorityQueue<Integer>();
            dmap.put(num, pq);
        }
        return pq;
    }
}

 

本文链接:http://bookshadow.com/weblog/2017/08/13/leetcode-split-array-into-consecutive-subsequences/
请尊重作者的劳动成果,转载请注明出处!书影博客保留对文章的所有权利。

如果您喜欢这篇博文,欢迎您捐赠书影博客: ,查看支付宝二维码