Loading

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

题目:https://leetcode-cn.com/problems/split-array-into-consecutive-subsequences/

题意:将一个排序好的数组分割成多个长度不小于3的连续子序列,例如:输入[1,2,2,3,3,4],有“1,2,3”、“2,3,4”,可以分割;输入[1,2,3,5,6,6],有“1,2,3,4,5,6”,“6”,不能分割。

官方题解:分割数组为连续子序列

思路:哈希表+最小堆。只要知道序列的最后一个数值和子序列长度就可以确定子序列。因此用哈希表存储最后一个元素和子序列长度。但可能出现多个以相同数字为结尾,如“5,5,5,5,5,5”,那么哈希表将无法直接使用。将哈希表的value存储为优先队列,队列元素代表长度,因为,数值x需要寻找以x-1为结尾的子序列,当出现多个x-1为结尾的子序列时,那么应该优先考虑较短的那个,因为题目要求长度至少为3。

代码:

class Solution {
    public boolean isPossible(int[] nums) {
        HashMap<Integer, PriorityQueue<Integer>> map = new HashMap<>();
        for(int n : nums){
            if(!map.containsKey(n)){
                map.put(n, new PriorityQueue<>());
            }
            if(map.containsKey(n-1)){
                int t = map.get(n-1).poll();
                if(map.get(n-1).isEmpty()){
                    map.remove(n-1);
                }
                map.get(n).offer(t+1);
            }else{
                map.get(n).offer(1);
            }
        }
        for(Map.Entry<Integer, PriorityQueue<Integer>> s : map.entrySet()){
            if(s.getValue().peek() < 3){
                return false;
            }
        }
        return true;
    }
}

 

posted @ 2020-12-04 13:50  yoyuLiu  阅读(175)  评论(0编辑  收藏  举报