FB面经prepare: task schedule II
followup是tasks是无序的.
一开始是有序的,比如说1, 1, 2, 1,一定要先执行第一个task1,然后等task1恢复,再执行第2个task1,再执行task2..... followup是无序的,就是不用按给的顺序执行,也就是可以先执行task1,然后task1还没恢复时,先执行task2, etc......
正确的做法应该是统计每个task的frequency,然后每次选frequency最高并且可以执行的task执行。
用maxHeap存每个task的剩余frequency
1 package TaskSchedule; 2 import java.util.*; 3 4 public class Solution2 { 5 public class Element { 6 int val; 7 int appr; 8 public Element(int value) { 9 this.val = value; 10 this.appr = 1; 11 } 12 } 13 14 public int schedule(int[] arr, int recover) { 15 HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); 16 PriorityQueue<Element> queue = new PriorityQueue<Element>(11, new Comparator<Element>() { 17 public int compare(Element e1, Element e2) { 18 return e2.appr-e1.appr; 19 } 20 }); 21 Element[] summary = new Element[10]; 22 for (int each : arr) { 23 if (summary[each] == null) { 24 summary[each] = new Element(each); 25 } 26 else summary[each].appr++; 27 } 28 for (Element elem : summary) { 29 if (elem != null) 30 queue.offer(elem); 31 } 32 33 34 35 36 int time = 0; 37 LinkedList<Element> temp = new LinkedList<Element>(); 38 while (!queue.isEmpty() || !temp.isEmpty()) { 39 if (!queue.isEmpty()) { 40 Element cur = queue.poll(); 41 if (!map.containsKey(cur.val)) { 42 map.put(cur.val, time+recover+1); 43 cur.appr--; 44 if (cur.appr > 0) temp.offer(cur); 45 while (!temp.isEmpty()) { 46 queue.offer(temp.poll()); 47 } 48 time++; 49 } 50 51 else { //map contains cur.val 52 if (time >= map.get(cur.val)) { //time is feasible 53 map.put(cur.val, time+recover+1); 54 cur.appr--; 55 if (cur.appr > 0) temp.offer(cur); 56 while (!temp.isEmpty()) { 57 queue.offer(temp.poll()); 58 } 59 time++; 60 } 61 else { //time is not feasible 62 temp.offer(cur); 63 } 64 } 65 } 66 67 else { //queue is empty, but temp is not empty 68 while (!temp.isEmpty()) { 69 queue.offer(temp.poll()); 70 } 71 time++; 72 } 73 } 74 return time; 75 } 76 77 78 /** 79 * @param args 80 */ 81 public static void main(String[] args) { 82 // TODO Auto-generated method stub 83 Solution2 sol = new Solution2(); 84 System.out.println(sol.schedule(new int[]{1, 1, 2, 2, 3, 3}, 2)); 85 } 86 87 }