leetcode659. Split Array into Consecutive Subsequences(659. 分割数组为连续子序列)/哈希+堆

题目:659. 分割数组为连续子序列

Given an array nums sorted in ascending order, return true if and only if you can split it into 1 or more subsequences such that each subsequence consists of consecutive integers and has length at least 3.

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 

Constraints:

  • 1 <= nums.length <= 10000

基本思想:哈希+堆

哈希表:用哈希表来保存已遍历的元素构成的连续子序列

  • 以子序列的最后一个元素作为哈希表的
  • 以子序列的长度作为哈希表的,(提示下:因为知道了连续子序列的长度和连续子序列的最后一个元素的值就能够确定一个子序列)

题目中还有一个条件,就是要求连续子序列的长度要大于3:

  • 为了达到该要求,每次向已有的子序列中增加元素时,都增加在最短的连续子序列后,因此,为了找到最短的连续子序列,将哈希表的值用堆这个数据结构

最终只需判断下哈希表中每一个键对应的最短的子序列的长度是否小于3即可

cpp版本

class Solution {
public:
    bool isPossible(vector<int>& nums) {
        unordered_map<int, priority_queue<int, vector<int>, greater<int>>> ump_pq;
        for(auto n : nums){
            if(ump_pq.find(n - 1) == ump_pq.end()){//没有可以合并的连续子序列
                ump_pq[n].push(1);
            }
            else{//存在可以合并的连续子序列
                int len = ump_pq[n-1].top();
                ump_pq[n - 1].pop();
                if(ump_pq[n - 1].size() == 0)
                    ump_pq.erase(n - 1);
                ump_pq[n].push(len + 1);
            }
        }
        for(auto ump: ump_pq){
            if(ump.second.top() < 3){
                return false;
            }
        }
        return true;
    }
};

python版本

class Solution:
    def isPossible(self, nums: List[int]) -> bool:
        ump_pq = defaultdict(list)
        for n in nums:
            if n - 1 in ump_pq.keys():
                length = ump_pq[n - 1][0]
                ump_pq[n - 1].pop(0)
                heapq.heapify(ump_pq[n - 1])
                if len(ump_pq[n - 1]) == 0:
                    ump_pq.pop(n - 1)
                ump_pq[n].append(length + 1)
                heapq.heapify(ump_pq[n])
            else:
                ump_pq[n].append(1)
                heapq.heapify(ump_pq[n])
        for key in ump_pq.keys():            
            if ump_pq[key][0] < 3:
                return False
        
        return True
已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页