1. 程式人生 > >659-將陣列分隔為連續子序列

659-將陣列分隔為連續子序列

Description

You are given an integer array sorted in ascending order (may contain duplicates), you need to split them into several subsequences, where each subsequences consist of at least 3 consecutive integers. Return whether you can make such a split.

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

Note:

  1. The length of the input is in range of [1, 10000]

問題描述

給定一個排好序的整數陣列(可能有重複元素), 你需要將它分隔為若干個子序列, 每個子序列至少由3個連續整陣列成。返回是否可以做出這樣的劃分

問題分析

  • freq儲存陣列元素對應個數
  • appendfreq用來判斷當前元素是否能夠插入到一個已經構建好的序列末端

遍歷nums,判斷一個元素是否能夠插入一個已經構建好的序列的末端,或者是否能作為新序列的起點,如果兩者都不可以,返回false。

解法

class Solution {
    public boolean isPossible(int[] nums) {
        Map<Integer, Integer> freq = new
HashMap<>(), appendfreq = new HashMap<>(); for (int i : nums) freq.put(i, freq.getOrDefault(i, 0) + 1); for (int i : nums) { //若當前元素個數為0, continue if (freq.get(i) == 0) continue; //大於0,表示當前元素可以插入到已經構建好的序列的末端 else if (appendfreq.getOrDefault(i, 0) > 0) { appendfreq.put(i, appendfreq.get(i) - 1); appendfreq.put(i + 1, appendfreq.getOrDefault(i + 1, 0) + 1); } //表示當前元素可以作為新序列的第一個元素 else if (freq.getOrDefault(i + 1, 0) > 0 && freq.getOrDefault(i + 2, 0) > 0) { freq.put(i + 1, freq.get(i + 1) - 1); freq.put(i + 2, freq.get(i + 2) - 1); //注意這裡,構建好一個序列,那麼該序列最後一個元素+1一定能插入到序列末端 appendfreq.put(i + 3, appendfreq.getOrDefault(i + 3, 0) + 1); } else return false; freq.put(i, freq.get(i) - 1); } return true; } }