当前位置:编程学习 > C/C++ >>

leetcode Insert Interval

First, this problem isn't about segment tree.
 
Second, I wanna share a terrible code without using the function insert and considering the case [[3,5],[12,15]], [6,6]
 
[cpp]  
/** 
 * 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 Solution {  
 public:  
  vector<Interval> insert(vector<Interval> &intervals, Interval newInterval) {  
    // Note: The Solution object is instantiated only once and is reused by each test case.  
    vector<Interval>::iterator it = intervals.begin(), start, end;  
    if (intervals.size() == 0) {  
      intervals.clear();  
      intervals.push_back(newInterval);  
    }  
    else if (newInterval.start <= intervals[0].start || newInterval.end >= intervals[intervals.size() - 1].end){  
      newInterval.start = min(newInterval.start, intervals[0].start);  
      newInterval.end = max(newInterval.end, intervals[intervals.size() - 1].end);  
      intervals.clear();  
      intervals.push_back(newInterval);  
    }  
    else {  
      while (it != intervals.end()) {  
        if (newInterval.start >= (*it).start && newInterval.start <= (*it).end)  
          start = it;  
        if (newInterval.end >= (*it).start && newInterval.end <= (*it).end) {  
          end = it;  
          break;  
        }  
        ++it;  
      }  
      int s1 = (*start).start;  
      int s2 = (*end).end;  
        
      it = start;  
      while (it != end) {  
        intervals.erase(it);  
        ++it;  
      }  
        
      (*it).start = s1;  
      (*it).end = s2;          
    }  
    return intervals;  
  }  
};  
When using insert, a concise code is like:
 
[cpp]  
/** 
 * 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 Solution {  
 public:  
  vector<Interval> insert(vector<Interval> &intervals, Interval newInterval) {  
    // Note: The Solution object is instantiated only once and is reused by each test case.  
    vector<Interval>::iterator it = intervals.begin();  
    while (it != intervals.end()) {  
      if (newInterval.start > it->end)   
        ++it;  
      else if (newInterval.end < it->start) {  
        intervals.insert(it, newInterval);  
        return intervals;  
      }  
      else{  
        newInterval.start = min(newInterval.start,it->start);  
        newInterval.end = max(newInterval.end,it->end);  
        it = intervals.erase(it);  
      }  
    }  
    intervals.insert(intervals.end(), newInterval);  
    return intervals;  
  }  
};  
 
 
 
补充:软件开发 , C++ ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,