Problem description:

log timestamp. implement start(id, timestamp), end(id, timestamp), print the log in ascending time order.

Solution:

Use map to store the location of the node.
Double linked list to fast insert and delete

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73

#include <unordered_map>
#include <list>
#include <string>
using namespace std;

class LogNode{
public:
int start;
int end;
string id;
LogNode* prev, *next;
LogNode(string _id, int _start){
id= _id;
start = _start;
end = -1;
}
};

class Log
{
public:
Log(){
head = new LogNode("", -1);
tail = new LogNode("", -1);
head->next = tail;
tail->prev = head;
};
LogNode *head, *tail;
//list<LogNode> l;
unordered_map<string, LogNode*> map; //id, timestamp
void add(string id, int timestamp);
void end(string id, int timestamp);
void print();
};

void Log::add(string id, int timestamp){
LogNode *newNode= new LogNode(id, timestamp);
map[id] = newNode;
auto tmp = tail->prev;
tmp->next = newNode;
newNode->prev = tmp;
newNode->next = tail;
tail->prev = newNode;
}

void Log::end(string id, int timestamp){
auto cur = map.find(id);
if(cur != map.end() && cur->second->end == -1){
cur->second->end = timestamp;
map.erase(id);
}
}

void Log::print(){
LogNode *cur = head->next;
while(cur != tail){
if(cur->end != -1){
printf("%s, start at %d, end at %d\n", cur->id.c_str(), cur->start, cur->end);
}
cur = cur->next;
}
}

int main(){
Log CLog;
CLog.add("1", 100);
CLog.add("2", 101);
CLog.end("2", 102);
CLog.end("1", 202);
CLog.print();
return 0;
}

time complexity: $O()$
space complexity: $O()$
reference: