进一步熟悉了STL吧 map的item类型是pair<const T1, T2>
lower_bound要提防还有等于的情况
STL不是随机就不能用-1
修改map部分写的还是太复杂,思路不清楚de了半天的bug
/**
* Definition for an interval.
* struct Interval {
* int start;
* int end;
* Interval() : start(0), end(0) {}
* Interval(int s, int e) : start(s), end(e) {}
* };
*/
class SummaryRanges {
public:
map<int, int> ans;
/** Initialize your data structure here. */
SummaryRanges() {
}
void addNum(int val) {
if(ans.size() == 0){
ans[val] = val;
}
auto i = ans.lower_bound(val), pre = i;
if(i != ans.begin()){
pre = --i;
i++;
}
if(i == ans.end()){
if(pre->second < val){
if(val == pre->second + 1)
pre->second ++;
else
ans[val] = val;
}
}
else if(i == ans.begin()){
if(i->first == val)
return;
if(i->first == val+1){
ans[val] = i->second;
ans.erase(val+1);
}
else ans[val] = val;
}
else{
if(val == i->first || val <= pre->second) return;
else if(val == i->first-1 && val == pre->second+1){
pre->second = i->second;
ans.erase(i);
}
else if(val == i->first-1){
ans[val] = i->second;
ans.erase(i);
}
else if(val == pre->second+1){
pre->second++;
}
else ans[val] = val;
}
}
vector<Interval> getIntervals() {
vector<Interval> a;
for(auto it = ans.begin(); it != ans.end(); ++it)
{
a.push_back(Interval(it->first, it->second));
}
return a;
}
};
/**
* Your SummaryRanges object will be instantiated and called as such:
* SummaryRanges obj = new SummaryRanges();
* obj.addNum(val);
* vector<Interval> param_2 = obj.getIntervals();
*/