leetcode - Insert Interval
2013-04-19 11:04 张汉生 阅读(158) 评论(0) 编辑 收藏 举报题目描述:点击此处
1 /** 2 * Definition for an interval. 3 * struct Interval { 4 * int start; 5 * int end; 6 * Interval() : start(0), end(0) {} 7 * Interval(int s, int e) : start(s), end(e) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 vector<Interval> insert(vector<Interval> &intervals, Interval newInterval) { 13 // Start typing your C/C++ solution below 14 // DO NOT write int main() function 15 int maxN = 1000000000; 16 vector<Interval> rlt; 17 if (intervals.empty()){ 18 rlt.push_back(newInterval); 19 return rlt; 20 } 21 intervals.push_back(newInterval); 22 vector<Interval>::iterator vi; 23 vector<Interval>::iterator pos =intervals.end()-1; 24 for (vi=intervals.end()-1-1; vi+1!=intervals.begin(); vi--){ 25 if ((*vi).start>(*(vi+1)).start){ 26 pos = vi; 27 Interval tmp = * vi; 28 *vi = *(vi+1); 29 *(vi+1) = tmp; 30 } 31 } 32 for (vi = pos-1; vi+1!=intervals.begin(); vi--){ 33 if ( (*vi).end>=(*pos).start ){ 34 (*pos).start = (*vi).start; 35 (*pos).end = (*pos).end > (*vi).end ? (*pos).end : (*vi).end; 36 (*vi).start = maxN; 37 } 38 else break; 39 } 40 for (vi = pos+1; vi!=intervals.end(); vi++){ 41 if ( (*vi).start<=(*pos).end ){ 42 (*pos).end = (*pos).end > (*vi).end ? (*pos).end : (*vi).end; 43 (*vi).start = maxN; 44 } 45 else break; 46 } 47 for (vi = intervals.begin(); vi!=intervals.end(); vi++){ 48 if ((*vi).start != maxN) 49 rlt.push_back(*vi); 50 } 51 return rlt; 52 } 53 };