forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
remove-zero-sum-consecutive-nodes-from-linked-list.cpp
62 lines (57 loc) · 1.5 KB
/
remove-zero-sum-consecutive-nodes-from-linked-list.cpp
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
// Time: O(n)
// Space: O(n)
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* removeZeroSumSublists(ListNode* head) {
ListNode dummy(0);
auto curr = &dummy;
dummy.next = head;
int prefix = 0;
OrderedDict<int, ListNode*> lookup;
while (curr) {
prefix += curr->val;
auto node = curr;
if (lookup.count(prefix)) {
node = lookup[prefix];
}
while (lookup.count(prefix)) {
lookup.popitem();
}
lookup[prefix] = node;
node->next = curr->next;
curr = curr->next;
}
return dummy.next;
}
private:
template<typename K, typename V>
class OrderedDict {
public:
bool count(const K& key) const {
return map_.count(key);
}
V& operator[](const K& key) {
if (!map_.count(key)) {
list_.emplace_front();
list_.begin()->first = key;
map_[key] = list_.begin();
}
return map_[key]->second;
}
void popitem() {
auto del = list_.front(); list_.pop_front();
map_.erase(del.first);
}
private:
list<pair<K, V>> list_;
unordered_map<K, typename list<pair<K, V>>::iterator> map_;
};
};