Exclusive Time of Processes

https://leetcode.com/discuss/interview-question/367064/Google-or-Phone-Screen-or-Exclusive-Time-of-Processes

Interval 类型的题目也可以用 line sweep 来做。

sort时如果x相同,右边界先处理更符合逻辑(左边界先得到的结果是一样的)。

#include <iostream>
#include <vector>
#include <unordered_set>
using namespace std;

struct node{
    int t;
    int id;
    int type; // start->1 end->-1
};

void exclusiveTime(vector<vector<int>> &input){
    vector<node> vec;
    for (auto x:input){
        vec.push_back({x[1],x[0],1});
        vec.push_back({x[2],x[0],-1});
    }
    sort(vec.begin(),vec.end(),[](node n1, node n2){
        if (n1.t==n2.t) return n1.type<n2.type;
        return n1.t<n2.t;
    });

    // for (auto x:vec){
    //     cout << x.t << ' ' << x.type << endl;
    // }
    unordered_set<int> active_set; // active ids
    int prev_t;
    unordered_map<int,int> total; // id -> total
    for (node n:vec){
        if (active_set.size()==1)
            total[*active_set.begin()]+=n.t-prev_t;

        if (n.type==1) active_set.insert(n.id);
        else active_set.erase(n.id);
        prev_t = n.t;
    }
    
    // if not appear then 0, code is omitted
    for (auto x:total) cout<<x.first<<' '<<x.second<<endl;
}


int main(){
    // vector<vector<int>> input{{1, 150, 300}, {2, 100, 200}, {3, 300, 350}};
    // vector<vector<int>> input{{1, 150, 150}};
    // vector<vector<int>> input{{1, 0, 300},{2,100,150},{3,200,250},{4,350,400}};
    vector<vector<int>> input{{1, 0, 300},{2,100,200},{3,250,400},{4,350,450}};
    exclusiveTime(input);
    return 0;
}

 

posted @ 2019-09-04 01:04  約束の空  阅读(166)  评论(0编辑  收藏  举报