621. Task Scheduler

Given a char array representing tasks CPU need to do. It contains capital letters A to Z where different letters represent different tasks.Tasks could be done without original order. Each task could be done in one interval. For each interval, CPU could finish one task or just be idle.

However, there is a non-negative cooling intervalnthat means between twosame tasks, there must be at least n intervals that CPU are doing different tasks or just be idle.

You need to return theleastnumber of intervals the CPU will take to finish all the given tasks.

Example 1:

Input:
 tasks = ["A","A","A","B","B","B"], n = 2

Output:
 8

Explanation:
 A -
>
 B -
>
 idle -
>
 A -
>
 B -
>
 idle -
>
 A -
>
 B.

Note:

  1. The number of tasks is in the range [1, 10000].
  2. The integer n is in the range [0, 100].

class Solution {
    public int leastInterval(char[] tasks, int n) {
        if (tasks == null || tasks.length == 0) return 0;
        int[] count = new int[26];
        for (char t : tasks){
            count[t - 'A']++;
        }

        PriorityQueue<Integer> pq = new PriorityQueue<>((a, b) -> (b - a));

        for (int c : count){
            if (c > 0){
                pq.offer(c);
            }
        }

        int time = 0;
        while (!pq.isEmpty()){
            int i = 0;
            List<Integer> list = new ArrayList<>();
            while (i <= n){
                if (!pq.isEmpty()){
                    if (pq.peek() > 1){
                        list.add(pq.poll() - 1);
                    }
                    else{
                        pq.poll();
                    }    
                }

                i++;
                time++;
                if (list.size() == 0 && pq.size() == 0) break;
            }

            for (int l : list){
                pq.offer(l);
            }
        }

        return time;
    }
}

results for ""

    No results matching ""