首页 > 代码库 > 插入区间
插入区间
以下是我自己的代码
vector<Interval> insert(vector<Interval> &intervals, Interval newInterval) { //write your code here vector<Interval> a; Interval b(0, 0); int x = 0; int y = 0; int m = 0; int n = intervals.size(); for (size_t i = 0; i != n; i++) { // 左边数字的判断 if (x == 0 && newInterval.start <= intervals[i].start) { b.start = newInterval.start; x = 1; } else if (x == 0 && newInterval.start <= intervals[i].end) { b.start = intervals[i].start; x = 1; } else if (x == 0){ b.start = intervals[i].start; } // 下面是右边数字的判断 if (y == 0 && newInterval.end < intervals[i].start) { b.end = newInterval.end; y = 1; } else if (y == 0 && newInterval.end == intervals[i].start) { b.end = intervals[i].end; y = 2; } else if (y == 0 && newInterval.end <= intervals[i].end) { b.end = intervals[i].end; y = 3; } else if (y == 0){ b.end = intervals[i].end; } if ( m == 0 && (x != 0 && y != 0) ) { m++; a.push_back(b); } if (y == 0 && x == 0) a.push_back(b); if (x != 0 && y != 0) { if (y == 2 || y == 3) { y = 1; } else a.push_back(intervals[i]); } } if (x == 0 && y == 0) { a.push_back(newInterval); } if (x != 0 && y == 0) { b.end = newInterval.end; a.push_back(b); } return a; }
别人家的代码
1 // Using Index 2 class Solution { 3 public: 4 vector<Interval> insert(vector<Interval> &intervals, Interval newInterval) { 5 vector<Interval> res = intervals; 6 int i = 0, overlap = 0, n = res.size(); 7 while (i < n) { 8 if (newInterval.end < res[i].start) break; 9 else if (newInterval.start > res[i].end) {} 10 else { 11 newInterval.start = min(newInterval.start, res[i].start); 12 newInterval.end = max(newInterval.end, res[i].end); 13 ++overlap; 14 } 15 ++i; 16 } 17 if (overlap > 0) res.erase(res.begin() + i - overlap, res.begin() + i); 18 res.insert(res.begin() + i - overlap, newInterval); 19 return res; 20 } 21 };
插入区间
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。