即向有序、不重疊的區間序列中插入一個區間。如區間產生重疊,則合併。求插入新區間後的區間序列。
如:A = [1,3],[6,9]
,插入[2,6]
,插入後新序列爲[1,9]
。數組
因爲序列有序,利用二分查找可在O(log N)
時間內找到待插入區間的位置區間,然後合併區間即刪除插入後產生的的重疊區間,因爲是在數組上進行刪除操做,時間複雜度爲O(N)
。即整體時間複雜度爲O(N)
,空間複雜度爲O(1)
。spa
typedef std::vector<Interval> ParamType; bool cmpStart(const Interval& a, const Interval& b) { return a.start > b.start; } bool cmpEnd(const Interval& a, const Interval& b) { return a.end < b.end; } class Solution { public: vector<Interval>& insert(vector<Interval>& intervals, Interval newInterval) { ParamType::reverse_iterator start(std::lower_bound(intervals.rbegin(), intervals.rend(), newInterval, cmpStart)); ParamType::iterator end(std::upper_bound(intervals.begin(), intervals.end(), newInterval, cmpEnd)); if (start != intervals.rend() && newInterval.start <= start->end) { if (end != intervals.end() && newInterval.end >= end->start) { start->end = end->end; intervals.erase(intervals.begin() + (intervals.size() - (start - intervals.rbegin())), end + 1); } else { start->end = newInterval.end; intervals.erase(intervals.begin() + (intervals.size() - (start - intervals.rbegin())), end); } } else { if (end != intervals.end() && newInterval.end >= end->start) { end->start = newInterval.start; intervals.erase(intervals.begin() + (intervals.size() - (start - intervals.rbegin())), end); } else { ParamType::iterator in = intervals.begin() + (intervals.size() - (start - intervals.rbegin())); if (in != end) { *in = newInterval; intervals.erase(in + 1, end); } else { intervals.insert(in, newInterval); } } } return intervals; } };
主要應用了二分查找的思想。code