参考:点击打开链接
followup是tasks是无序的.
一开始是有序的,比如说1, 1, 2, 1,一定要先执行第一个task1,然后等task1恢复,再执行第2个task1,再执行task2..... followup是无序的,就是不用按给的顺序执行,也就是可以先执行task1,然后task1还没恢复时,先执行task2, etc......
这次得记录每个task的frequency,设计一个map,同时,用priorityQueue存最大的frequency,一个queue来存暂时超时不能运行的task
public class Element {
int val;
int appr;
public Element(int value, int appr) {
this.val = value;
this.appr = appr;
}
}
//public int schedule(int[] arr, int recover) {
public String schedule2(int[] arr, int recover) {
HashMap<Integer/*tack type*/, Integer/*time*/> map = new HashMap<Integer, Integer>();
PriorityQueue<Element> queue = new PriorityQueue<Element>(11, new Comparator<Element>() {
public int compare(Element e1, Element e2) {
return e2.appr-e1.appr;
}
});
HashMap<Integer/*tack type*/, Integer/*frequence*/> freMap = new HashMap<Integer, Integer>();
for (int each : arr) {
if (freMap.containsKey(each)) {
freMap.put(each, freMap.get(each) + 1);
} else {
freMap.put(each, 1);
}
}
for (Map.Entry<Integer, Integer> entry: freMap.entrySet()) {
queue.offer(new Element(entry.getKey(), entry.getValue()));
}
int time = 0;
Queue<Element> temp = new LinkedList<Element>();
StringBuilder sb = new StringBuilder();
while (!queue.isEmpty() || !temp.isEmpty()) {
if (!queue.isEmpty()) {
Element cur = queue.poll();
if (!map.containsKey(cur.val)) {
map.put(cur.val, time+recover+1);
cur.appr--;
if (cur.appr > 0) temp.offer(cur);
while (!temp.isEmpty()) {
queue.offer(temp.poll());
}
time++;
sb.append(cur.val + ",");
}
else { //map contains cur.val
if (time >= map.get(cur.val)) { //time is feasible
map.put(cur.val, time+recover+1);
cur.appr--;
if (cur.appr > 0) temp.offer(cur);
while (!temp.isEmpty()) {
queue.offer(temp.poll());
}
time++;
sb.append(cur.val + ",");
}
else { //time is not feasible
temp.offer(cur);
}
}
}
else { //queue is empty, but temp is not empty
while (!temp.isEmpty()) {
queue.offer(temp.poll());
}
time++;
sb.append("_,");
}
}
//return time;
System.out.println("time:" + time + " strLen:" + sb.length());
return sb.toString();
}

本文介绍了一种基于优先级队列的任务调度算法实现方法。通过使用哈希映射记录任务类型及其执行时间,并利用优先级队列按频率排序任务,确保高频率任务优先执行。此外,还介绍了如何处理任务超时情况。
3006

被折叠的 条评论
为什么被折叠?



