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

猜你喜欢

转载自blog.csdn.net/weixin_38970751/article/details/85332200