forked from chuyi2007/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInsertIntervals.java
More file actions
38 lines (38 loc) · 1.24 KB
/
InsertIntervals.java
File metadata and controls
38 lines (38 loc) · 1.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/**
* Definition for an interval.
* public class Interval {
* int start;
* int end;
* Interval() { start = 0; end = 0; }
* Interval(int s, int e) { start = s; end = e; }
* }
*/
public class Solution {
public ArrayList<Interval> insert(ArrayList<Interval> intervals, Interval newInterval) {
// Start typing your Java solution below
// DO NOT write main() function
int size = intervals.size();
int s = -1, e = -1;
for(int i = 0; i < size; ++i){
if(s == -1 && intervals.get(i).end >= newInterval.start)
s = i;
if(intervals.get(i).start <= newInterval.end)
e = i;
}
if(s == -1){
intervals.add(newInterval);
return intervals;
}
if(e == -1){
intervals.add(0, newInterval);
return intervals;
}
//if(s == e) return intervals;
int f = Math.min(intervals.get(s).start, newInterval.start);
int l = Math.max(intervals.get(e).end, newInterval.end);
newInterval = new Interval(f, l);
intervals.subList(s, e + 1).clear();
intervals.add(s, newInterval);
return intervals;
}
}