效率开始下降,实验室聚餐一开始推了,发现他们全都去了又开始怀疑是不是该去,看了看窗外的太阳然后又放弃了,纠结如我。
这题很简单,二分查找输入(但我总觉得可以用bst做,但是想想,insert的时间复杂度O(h)+遍历复杂度O(n))比二分查找O(logN)多(当然这个不含有vector ans的erase、insert操作)(ps. insert也是O(n)的复杂度,大神说在里面插入用list好了,头插用deque)
class SummaryRanges {
public:
/** Initialize your data structure here. */
struct Interval {
int start;
int end;
Interval() { start = 0; end = 0; }
Interval(int s, int e) {
start = s; end = e;
}
};
vector<Interval> temp;
SummaryRanges() {
}
void addNum(int val) {
if(temp.empty()){
temp.push_back(Interval(val, val));
return;
}
int n = (int)temp.size();
int low = 0, high = n - 1;
while(low < high){
int mid = ceil(1.0*(low + high) /2);
if(temp[mid].start > val) high = mid - 1;
else low = mid;
}
if(val > temp[low].end){
if(low + 1 < n){
if(val > temp[low].end + 1 && val + 1 < temp[low + 1].start){
Interval A(val, val);
temp.insert(temp.begin() + low + 1 ,A);
}
else if(val > temp[low].end + 1 && val + 1 >= temp[low + 1].start){
Interval A(val, temp[low+1].end);
temp.insert(temp.begin() + low + 1, A);
temp.erase(temp.begin() + low + 2);
}
else if(val <= temp[low].end + 1 && val + 1 < temp[low + 1].start){
Interval A(temp[low].start, val);
temp.insert(temp.begin() + low, A);
temp.erase(temp.begin() + low + 1);
}
else{
Interval A(temp[low].start, temp[low + 1].end);
temp.insert(temp.begin() + low, A);
temp.erase(temp.begin() + low + 1);
temp.erase(temp.begin() + low + 1);
}
}
else{
if(val > temp[low].end + 1){
Interval A(val, val);
temp.push_back(A);
}else{
Interval A(temp.back().start, val);
temp.pop_back();
temp.push_back(A);
}
}
}
else if(low == 0 && val < temp[low].start){
if(val == temp[low].start - 1){
temp.insert(temp.begin(), Interval(val, temp[low].end));
temp.erase(temp.begin() + 1);
}
if(val < temp[low].start - 1){
temp.insert(temp.begin(), Interval(val, val));
}
}
}
vector<Interval> getIntervals() {
return temp;
}
};
直接上代码