Leetcode: Insert Interval

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].

第二遍做法:

 1 /**

 2  * Definition for an interval.

 3  * public class Interval {

 4  *     int start;

 5  *     int end;

 6  *     Interval() { start = 0; end = 0; }

 7  *     Interval(int s, int e) { start = s; end = e; }

 8  * }

 9  */

10 public class Solution {

11     public List<Interval> insert(List<Interval> intervals, Interval newInterval) {

12         if (intervals.size() == 0) {

13             intervals.add(newInterval);

14             return intervals;

15         }

16         ArrayList<Interval> res = new ArrayList<Interval>();

17         int cur = 0;

18         while (cur < intervals.size() && intervals.get(cur).end < newInterval.start) {

19             res.add(intervals.get(cur));

20             cur++;

21         }

22         while (cur < intervals.size() && intervals.get(cur).start <= newInterval.end) {

23             newInterval.start = Math.min(newInterval.start, intervals.get(cur).start);

24             newInterval.end = Math.max(newInterval.end, intervals.get(cur).end);

25             cur++;

26         }

27         res.add(newInterval);

28         while (cur < intervals.size()) {

29             res.add(intervals.get(cur));

30             cur++;

31         }

32         return res;

33     }

34 }

第一遍的做法:

 1 public ArrayList<Interval> insert(ArrayList<Interval> intervals, Interval newInterval) {

 2     ArrayList<Interval> res = new ArrayList<Interval>();

 3     if(intervals.size()==0)

 4     {

 5         res.add(newInterval);

 6         return res;

 7     }

 8     int i=0;

 9     while(i<intervals.size() && intervals.get(i).end<newInterval.start)

10     {

11         res.add(intervals.get(i));

12         i++;

13     }

14     if(i<intervals.size())

15         newInterval.start = Math.min(newInterval.start, intervals.get(i).start);

16     res.add(newInterval);

17     while(i<intervals.size() && intervals.get(i).start<=newInterval.end)

18     {

19         newInterval.end = Math.max(newInterval.end, intervals.get(i).end);

20         i++;

21     }

22     while(i<intervals.size())

23     {

24         res.add(intervals.get(i));

25         i++;

26     }

27     return res;

28 }

 

你可能感兴趣的:(LeetCode)