-
Notifications
You must be signed in to change notification settings - Fork 0
/
leet352.cpp
73 lines (68 loc) · 1.74 KB
/
leet352.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
63
64
65
66
67
68
69
70
71
72
73
#include <iostream>
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <string.h>
#include <algorithm>
#include <stdio.h>
using namespace std;
class SummaryRanges {
map<int,int> dic;
public:
SummaryRanges() {
;
}
void addNum(int val) {
auto intervall1 = dic.upper_bound(val);
auto intervall0 = intervall1==dic.begin()?dic.end():prev(intervall1);
if(intervall0!=dic.end() && intervall0->first<=val && val<=intervall0->second)
return;
else {
bool left_side = intervall0!=dic.end() && intervall0->second==val-1;
bool right_side = intervall1!=dic.end() && intervall1->first==val+1;
if(left_side && right_side)
{
int new_start = intervall0->first;
int new_end = intervall1->second;
dic.erase(intervall1);
dic.erase(intervall0);
dic[new_start]= new_end;
}
else if(left_side)
{
intervall0->second ++;
}
else if(right_side)
{
int new_end = intervall1->second;
dic.erase(intervall1);
dic[val] = new_end;
}
else
dic[val] = val;
}
}
vector<vector<int>> getIntervals() {
vector<vector<int>> re;
for(auto v:dic)
{
vector<int> t = {v.first,v.second};
re.emplace_back(t);
}
return re;
}
};
int main()
{
SummaryRanges sr;
sr.addNum(1);
sr.getIntervals();
sr.addNum(3);
sr.getIntervals();
sr.addNum(7);
sr.getIntervals();
sr.addNum(2);
sr.addNum(6);
return 0;
}