您的位置:首页 > 其它

FB面经prepare: task schedule II

2016-01-11 07:12 423 查看
followup是tasks是无序的.
一开始是有序的,比如说1, 1, 2, 1,一定要先执行第一个task1,然后等task1恢复,再执行第2个task1,再执行task2..... followup是无序的,就是不用按给的顺序执行,也就是可以先执行task1,然后task1还没恢复时,先执行task2, etc......


正确的做法应该是统计每个task的frequency,然后每次选frequency最高并且可以执行的task执行。

用maxHeap存每个task的剩余frequency

package TaskSchedule;
import java.util.*;

public class Solution2 {
public class Element {
int val;
int appr;
public Element(int value) {
this.val = value;
this.appr = 1;
}
}

public int schedule(int[] arr, int recover) {
HashMap<Integer, Integer> 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;
}
});
Element[] summary = new Element[10];
for (int each : arr) {
if (summary[each] == null) {
summary[each] = new Element(each);
}
else summary[each].appr++;
}
for (Element elem : summary) {
if (elem != null)
queue.offer(elem);
}

int time = 0;
LinkedList<Element> temp = new LinkedList<Element>();
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++;
}

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++;
}
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++;
}
}
return time;
}

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Solution2 sol = new Solution2();
System.out.println(sol.schedule(new int[]{1, 1, 2, 2, 3, 3}, 2));
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: