|
| 1 | +package com.fishercoder.solutions; |
| 2 | + |
| 3 | +import java.util.*; |
| 4 | + |
| 5 | +/** |
| 6 | + * 659. Split Array into Consecutive Subsequences |
| 7 | + * |
| 8 | + * You are given an integer array sorted in ascending order (may contain duplicates), |
| 9 | + * you need to split them into several subsequences, |
| 10 | + * where each subsequences consist of at least 3 consecutive integers. Return whether you can make such a split. |
| 11 | +
|
| 12 | + Example 1: |
| 13 | + Input: [1,2,3,3,4,5] |
| 14 | + Output: True |
| 15 | + Explanation: |
| 16 | + You can split them into two consecutive subsequences : |
| 17 | + 1, 2, 3 |
| 18 | + 3, 4, 5 |
| 19 | +
|
| 20 | + Example 2: |
| 21 | + Input: [1,2,3,3,4,4,5,5] |
| 22 | + Output: True |
| 23 | + Explanation: |
| 24 | + You can split them into two consecutive subsequences : |
| 25 | + 1, 2, 3, 4, 5 |
| 26 | + 3, 4, 5 |
| 27 | +
|
| 28 | + Example 3: |
| 29 | + Input: [1,2,3,4,4,5] |
| 30 | + Output: False |
| 31 | +
|
| 32 | + Note: |
| 33 | + The length of the input is in range of [1, 10000] |
| 34 | + */ |
| 35 | + |
| 36 | +public class _659 { |
| 37 | + |
| 38 | + /**reference: https://discuss.leetcode.com/topic/99187/java-o-n-time-o-n-space*/ |
| 39 | + public boolean isPossible(int[] nums) { |
| 40 | + Map<Integer, Integer> freqMap = new HashMap<>(); |
| 41 | + for (int i : nums) { |
| 42 | + freqMap.put(i, freqMap.getOrDefault(i, 0) + 1); |
| 43 | + } |
| 44 | + Map<Integer, Integer> appendFreqMap = new HashMap<>(); |
| 45 | + for (int i : nums) { |
| 46 | + if (freqMap.get(i) == 0) { |
| 47 | + continue; |
| 48 | + } else if (appendFreqMap.getOrDefault(i, 0) > 0) { |
| 49 | + appendFreqMap.put(i, appendFreqMap.get(i) - 1); |
| 50 | + appendFreqMap.put(i+1, appendFreqMap.getOrDefault(i+1, 0) + 1); |
| 51 | + } else if (freqMap.getOrDefault(i+1, 0) > 0 && freqMap.getOrDefault(i+2, 0) > 0) { |
| 52 | + freqMap.put(i+1, freqMap.get(i+1) - 1); |
| 53 | + freqMap.put(i+2, freqMap.get(i+2) - 1); |
| 54 | + appendFreqMap.put(i+3, appendFreqMap.getOrDefault(i+3, 0) + 1); |
| 55 | + } else return false; |
| 56 | + freqMap.put(i, freqMap.get(i) - 1); |
| 57 | + } |
| 58 | + return true; |
| 59 | + } |
| 60 | + |
| 61 | +} |
0 commit comments