Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Latest commit

 

History

History
History
57 lines (55 loc) · 1.73 KB

File metadata and controls

57 lines (55 loc) · 1.73 KB
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
/*
Author: King, wangjingui@outlook.com
Date: Dec 20, 2014
Problem: Merge Intervals
Difficulty: Medium
Source: https://oj.leetcode.com/problems/merge-intervals/
Notes:
Given a collection of intervals, merge all overlapping intervals.
For example,
Given [1,3],[2,6],[8,10],[15,18],
return [1,6],[8,10],[15,18].
Solution: 1. Sort in ascending order of 'start'.
2. Traverse the 'intervals', merge or push...
*/
/**
* 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 List<Interval> merge(List<Interval> intervals) {
Comparator<Interval> comp = new Comparator<Interval>(){
public int compare(Interval a, Interval b) {
if(a.start < b.start) {
return -1;
}else if(a.start > b.start){
return 1;
} else {
if (a.end < b.end) return -1;
else if (a.end > b.end) return 1;
return 0;
}
}
};
ArrayList<Interval> res = new ArrayList<Interval>();
int N = intervals.size();
if (N <= 1) return intervals;
Collections.sort(intervals, comp);
Interval last = intervals.get(0);
for (int i = 0; i < N; ++i) {
if (intervals.get(i).start > last.end) {
res.add(last);
last = intervals.get(i);
} else {
last.end = Math.max(last.end, intervals.get(i).end);
}
}
res.add(last);
return res;
}
}
Morty Proxy This is a proxified and sanitized view of the page, visit original site.