zoukankan      html  css  js  c++  java
  • [LC] 659. Split Array into Consecutive Subsequences

    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
    
    class Solution {
        public boolean isPossible(int[] nums) {
            Map<Integer, Integer> freqMap = new HashMap<>();
            Map<Integer, Integer> hypoMap = new HashMap<>();
            for (int num: nums) {
                freqMap.put(num, freqMap.getOrDefault(num, 0) + 1);
            }
            
            for (int num : nums) {
                // base case
                if (freqMap.get(num) == 0) {
                    continue;
                }
                if (hypoMap.getOrDefault(num, 0) > 0) {
                    hypoMap.put(num, hypoMap.get(num) - 1);
                    freqMap.put(num, freqMap.get(num) - 1);
                    hypoMap.put(num + 1, hypoMap.getOrDefault(num + 1, 0) + 1);
                } else if (freqMap.getOrDefault(num, 0) > 0 && freqMap.getOrDefault(num + 1, 0) > 0 && freqMap.getOrDefault(num + 2, 0) > 0) {
                    freqMap.put(num, freqMap.get(num) - 1);
                    freqMap.put(num + 1, freqMap.get(num + 1) - 1);
                    freqMap.put(num + 2, freqMap.get(num + 2) - 1);
                    hypoMap.put(num + 3, hypoMap.getOrDefault(num + 3, 0) + 1);
                } else {
                    return false;
                }
            }
            return true;
        }
    }
  • 相关阅读:
    YAOI Summer Round #4 (Div.2) 题解
    2021 暑假集训(福建师大附中)
    YAOI Round #7 题解
    YAOI Round #5 题解
    插头DP
    四边形不等式
    YAOI Round #3 题解
    关于 2020 年
    图论相关性质和结论(基础)
    斜率优化 DP :Luogu P2365 P5785「SDOI2012」任务安排 & 弱化版
  • 原文地址:https://www.cnblogs.com/xuanlu/p/12307000.html
Copyright © 2011-2022 走看看