LeetCode 57 Insert Interval

时间:2019-09-05
本文章向大家介绍LeetCode 57 Insert Interval,主要包括LeetCode 57 Insert Interval使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

题目
插入一个再排序,没有一点难度

struct Node
{
    int x;
    int y;
    Node(){}
    Node(int x,int y){
        this->x = x;
        this->y =y;
    }
}a[100005];

int Compare(Node a,Node b)
{
    if(a.x==b.x)
    {
       return a.y<b.y;
    }
    return a.x<b.x;
}
class Solution {
public:
    vector<vector<int>> insert(vector<vector<int>>& intervals, vector<int>& newInterval) {
        
        vector<vector<int>> ans;
        vector<int> res;
        if(intervals.size()==0)
        {
            if(newInterval.size()==0)
                return ans;
            else
            {
                ans.push_back(newInterval);
                return ans;
            }
        }
       
            
        int pos=0;
        
        for(int i=0;i<intervals.size();i++)
        {
            a[pos++] = Node(intervals[i][0],intervals[i][1]);
        }
        
        if(newInterval.size()!=0)
            a[pos++] = Node(newInterval[0],newInterval[1]);
        
        sort(a,a+pos,Compare);
        
        
        int start =a[0].x;
        int end=a[0].y;
        for(int i=1;i<pos;i++)
        {
            if(a[i].x<=end)
            {
                end=max(end,a[i].y);
            }
            else
            {
                res.clear();
                res.push_back(start);
                res.push_back(end);
                ans.push_back(res);
                
                start=a[i].x;
                end=a[i].y;
            }
        }
        
        res.clear();
        res.push_back(start);
        res.push_back(end);
        ans.push_back(res);
        
        return ans;
    }
};

原文地址:https://www.cnblogs.com/dacc123/p/11465512.html