1. 程式人生 > >Split Array

Split Array

 

題目1 : Split Array

時間限制:10000ms

單點時限:1000ms

記憶體限制:256MB

描述

You are given an sorted integer array A and an integer K. Can you split A into several sub-arrays that each sub-array has exactly K continuous increasing integers.

For example you can split {1, 1, 2, 2, 3, 3, 3, 4, 4, 5, 5, 6}  into {1, 2, 3}, {1, 2, 3}, {3, 4, 5}, {4, 5, 6}.  

輸入

The first line contains an integer T denoting the number of test cases. (1 <= T <= 5)

Each test case takes 2 lines. The first line contains an integer N denoting the size of array A and an integer K. (1 <= N <= 50000, 1 <= K <= N)

The second line contains N integers denoting array A. (1 <= Ai <= 100000)

輸出

For each test case output YES or NO in a separate line.

 

假設X是A陣列中的最小值。那麼我們就檢查A陣列中是不是包含子陣列B = [X, X+1, X+2, ... X+K-1]。

如果A不包含B,那麼X一定不能湊成"順子",直接返回NO。

否則我們可以把B從A中刪除,然後重複這一步驟即可。

樣例輸入

2  
12 3 
1 1 2 2 3 3 3 4 4 5 5 6  
12 4  

貪心

1 1 2 2 3 3 3 4 4 5 5 6

樣例輸出

YES  
NO
import java.util.Scanner;
import java.util.Map;
import java.util.HashMap;
import java.util.Queue;
import java.util.LinkedList;

public class Main {
    private static final String YES = "YES";
    private static final String NO = "NO";
    
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int numTestCases = in.nextInt();
        
        for (int i = 0; i < numTestCases; i++) {
            int n = in.nextInt();
            int k = in.nextInt();
            int[] array = readArray(in, n);
            
            if (isConsecutive(array, k)) {
                System.out.println(YES);
            } else {
                System.out.println(NO);
            }
        }
    }
    
    private static int[] readArray(Scanner in, int n) {
        int[] result = new int[n];
        
        for (int i = 0; i < n; i++) {
            result[i] = in.nextInt();
        }
        
        return result;
    }
    
    private static boolean isConsecutive(int[] array, int k) {
        Map<Integer, Queue<Integer>> positions = new HashMap<>();
        int length = array.length;
        boolean[] visited = new boolean[length];
        // Cache every position
        for (int i = 0; i < length; i++) {
            positions.computeIfAbsent(array[i], key -> new LinkedList<>()).offer(i);
        }
        // Check
        for (int i = 0; i < length; i++) {
            if (visited[i]) {
                continue;
            } else {
                for (int target = array[i], ct = 0; ct < k; target++, ct++) {
                    Queue<Integer> position = positions.get(target);
                    
                    if (position == null || position.isEmpty()) {
                        return false;
                    } else {
                        int p = position.poll();
                        visited[p] = true;
                    }
                }
            }
        }
        
        return true;
    }
}