621. Task Scheduler && 358. Rearrange String k Distance Apart

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 interval n that means between two same tasks, there must be at least n intervals that CPU are doing different tasks or just be idle.

You need to return the least number 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]

 Greedy Queue 

 

public class Solution {
    public int leastInterval(char[] tasks, int n) {
        if (tasks.length == 0)
          return 0;

        HashMap<Character, Integer> taskMap = new HashMap<>();
        for (char t : tasks) {
          taskMap.put(t, taskMap.getOrDefault(t, 0) + 1);
        }
        PriorityQueue<Map.Entry<Character, Integer>> toDo = new PriorityQueue<>(
            (a, b) -> a.getValue() == b.getValue()
                ? a.getKey() - b.getKey()
                : b.getValue() - a.getValue());
        toDo.addAll(taskMap.entrySet());

        int steps = 0;
        while (!toDo.isEmpty()) {
          List<Map.Entry<Character, Integer>> processed = new ArrayList<>();
          int currentRoundSteps = n;
          while (currentRoundSteps >= 0 && !toDo.isEmpty()) {
            Map.Entry<Character, Integer> item = toDo.poll();
            --currentRoundSteps;
            ++steps;
            if (item.getValue() > 1) {
              item.setValue(item.getValue() - 1);
              processed.add(item);
            }
          }
          if (!processed.isEmpty()) {
            steps += currentRoundSteps + 1;
          }
          toDo.addAll(processed);
        }

        return steps;
    }
}

 

358. Rearrange String k Distance Apart

Given a non-empty string str and an integer k, rearrange the string such that the same characters are at least distance k from each other.

All input strings are given in lowercase letters. If it is not possible to rearrange the string, return an empty string "".

Example 1:

str = "aabbcc", k = 3

Result: "abcabc"

The same letters are at least distance 3 from each other.

Example 2:

str = "aaabc", k = 3 

Answer: ""

It is not possible to rearrange the string.

Example 3:

str = "aaadbbcc", k = 2

Answer: "abacabcd"

Another possible answer is: "abcabcda"

The same letters are at least distance 2 from each other.

 

 

 
posted @ 2017-07-18 22:43  新一代的天皇巨星  阅读(211)  评论(0编辑  收藏  举报