Process Sequence
Input: logs = [(1, 1234), (2, 1234)], queries = [2]Output: [2]Input: logs = [(1, 1234), (1, 1235)], queries = [1234]Output: [1]/**
* Definition of Interval:
* public class Interval {
* int start, end;
* Interval(int start, int end) {
* this.start = start;
* this.end = end;
* }
* }
*/
public class Solution {
class TimePoint {
int time;
int type;
public TimePoint (int time, int type) {
this.time = time;
this.type = type;
}
}
/**
* @param logs: Sequence of processes
* @param queries: Sequence of queries
* @return: Return the number of processes
*/
public List<Integer> numberOfProcesses(List<Interval> logs, List<Integer> queries) {
List<TimePoint> list = new ArrayList<>();
// 将所有时间点做成一个新的object,加入list
for (Interval log : logs) {
list.add(new TimePoint(log.start, 0)); // start记做0,这样最小
list.add(new TimePoint(log.end, 1));
}
for (int query : queries) list.add(new TimePoint(query, 2)); // 询问点记做2,这样最大
// 对list里的元素排序
list.sort((t1, t2) -> {
if (t1.time == t2.time) return Integer.compare(t1.type, t2.type);
else return Integer.compare(t1.time, t2.time);
});
int count = 0;
// map用来储存对每个询问点,有多少个进程在同时进行
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < list.size(); i++) {
TimePoint t = list.get(i);
if (t.type == 0) count++;
else if (t.type == 1) count--;
if (t.type == 2) map.put(t.time, count);
}
List<Integer> res = new ArrayList<>();
for (int q : queries) res.add(map.get(q));
return res;
}
}Last updated