240
笔下虽有千言,胸中实无一策

30 Day Challenge Day 22 | Leetcode 57. Insert Interval

题解

Medium

避免使用 erase ,复杂度较高。

class Solution {
public:
    vector<vector<int>> insert(vector<vector<int>>& intervals, vector<int>& newInterval) {
        vector<vector<int>> res;
        int i = 0;
        
        while(i < intervals.size()) {
            if(newInterval[1] < intervals[i][0]) {
                break;
            } else if(newInterval[0] > intervals[i][1]) {
                res.push_back(intervals[i]);
                i++;
            } else {
                newInterval[0] = min(intervals[i][0], newInterval[0]);
                newInterval[1] = max(intervals[i][1], newInterval[1]);
                i++;
            }
        }
        
        res.push_back(newInterval);
        
        while(i < intervals.size()) {
            res.push_back(intervals[i]);
            i++;
        }
        
        return res;  
    }
};
posted @ 2020-10-10 11:23  CasperWin  阅读(96)  评论(0编辑  收藏  举报