leetcode 57. Insert Interval

来源:互联网 发布:手机控制电脑 python 编辑:程序博客网 时间:2024/06/06 14:07

Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).

You may assume that the intervals were initially sorted according to their start times.

Example 1:
Given intervals [1,3],[6,9], insert and merge [2,5] in as [1,5],[6,9].

Example 2:
Given [1,2],[3,5],[6,7],[8,10],[12,16], insert and merge [4,9] in as [1,2],[3,10],[12,16].

This is because the new interval [4,9] overlaps with [3,5],[6,7],[8,10].

区间合并,这个和上一道题的做法一样,这里我们有旋转插入排序,而是直接添加然后排序,最后合并。

代码如下:

import java.util.ArrayList;import java.util.Comparator;import java.util.List;/*class Interval{    int start;    int end;    Interval() { start = 0; end = 0; }    Interval(int s, int e) { start = s; end = e; }}*/public class Solution {    public List<Interval> insert(List<Interval> intervals, Interval newInterval)    {        intervals.add(newInterval);        if(intervals==null || intervals.size()<=1)            return intervals;        List<Interval> res=new ArrayList<Interval>();        intervals.sort(new Comparator<Interval>() {            @Override            public int compare(Interval o1, Interval o2) {                return o1.start-o2.start;            }        });        Interval pre=intervals.get(0);        for(int i=1;i<intervals.size();i++)        {            Interval now=intervals.get(i);            if(pre.end>=now.start)                pre=new Interval(pre.start, Math.max(pre.end, now.end));            else            {                res.add(pre);                pre=now;            }        }        res.add(pre);        return res;    }}

和上一道题一样,先插入,然后排序,最后合并即可

代码如下:

#include <iostream>#include <vector>#include <algorithm>using namespace std;/*struct Interval{int start;int end;Interval() : start(0), end(0) {}Interval(int s, int e) : start(s), end(e) {}};*/bool cmp(Interval a, Interval b){    if (a.start < b.start)        return true;    else        return false;}class Solution {public:    vector<Interval> insert(vector<Interval>& in, Interval newInterval)    {        in.push_back(newInterval);        if (in.size() <= 1)            return in;        vector<Interval> res;        sort(in.begin(),in.end(),cmp);        Interval pre = in[0];        for (int i = 1; i < in.size(); i++)        {            Interval now = in[i];            if (pre.end < now.start)            {                res.push_back(pre);                pre = now;            }            else                pre = Interval(pre.start,max(pre.end,now.end));        }        res.push_back(pre);        return res;    }};
原创粉丝点击