首页 > 其他 > 详细

[LC] 659. Split Array into Consecutive Subsequences

时间:2020-02-14 13:48:09      阅读:66      评论:0      收藏:0      [点我收藏+]

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;
    }
}

 

[LC] 659. Split Array into Consecutive Subsequences

原文:https://www.cnblogs.com/xuanlu/p/12307000.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!