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;
    }
};
posted @ 2019-09-05 13:51  Shendu.CC  阅读(90)  评论(0编辑  收藏  举报