首页 > 其他 > 详细

LeetCode 57 Insert Interval

时间:2019-09-05 14:12:11      阅读:73      评论:0      收藏:0      [点我收藏+]

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

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;
    }
};

LeetCode 57 Insert Interval

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!