FB面经prepare: Task Schedule

每种task都有冷却时间,比如task1执行后,要经过interval时间后才能再次执行,求总共所需时间。

用HashMap保存每一个task的下一次可以开始执行的最早时间

 1 package TaskSchedule;
 2 import java.util.*;
 3 
 4 public class Solution {
 5     public int schedule(int[] str, int recover) {
 6         if (str==null || str.length==0) return 0;
 7         if (recover == 0) return str.length;
 8         int pos = 0;
 9         int time = 0;
10         HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
11         for (; pos<str.length; pos++) {
12             int cur = str[pos];
13             if (!map.containsKey(cur)) {
14                 map.put(cur, time+recover+1);
15             }
16             else {
17                 int lastApr = map.get(cur);
18                 if (time >= lastApr) {
19                     map.put(cur, time);
20                 }
21                 else {
22                     pos--;
23                 }
24             }
25             time++;
26         }
27         return time;
28     }
29 
30     /**
31      * @param args
32      */
33     public static void main(String[] args) {
34         // TODO Auto-generated method stub
35         Solution sol = new Solution();
36         System.out.println(sol.schedule(new int[]{1, 2, 3, 1, 2, 3}, 3));
37 
38     }
39 
40 }
原文地址:https://www.cnblogs.com/EdwardLiu/p/5120090.html