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)); } }
相关文章推荐
- FB面经prepare: Task Schedule
- 循环引用的问题...
- 家庭经营的目的
- PCB导网表及常见问题处理
- Poj 1743Musical Theme|后缀数组|二分答案
- LeetCode Expression Add Operators
- Java开发中的23种设计模式详解
- LeetCode Integer to English Words
- ansible的原理与初步使用
- LeetCode Single Number III
- [dp]POJ 2229 Sumsets 解题报告
- GL中如何让画的点为圆形
- sklearn常见分类器的效果比较
- LeetCode Different Ways to Add Parentheses
- Android列表控件ListView详解
- Java练习1_统计代码有效行
- 用matplotlib获取雅虎股票数据并作图
- map那些事(1)
- apache中301和403优先级
- Linux下snmp常用的OID,用做服务器监控