Skip to content

Commit 8ee0c61

Browse files
committed
merge intervals solution
1 parent 2fdc800 commit 8ee0c61

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
import java.util.Arrays;
2+
import java.util.HashMap;
3+
import java.util.Map;
4+
5+
class Solution {
6+
public int[][] merge(int[][] intervals) {
7+
// 1. [0]๋ฒˆ์งธ ์œ„์ฃผ๋กœ ์˜ค๋ฆ„์ฐจ์ˆœ ์ •๋ ฌํ•œ๋‹ค.
8+
Arrays.sort(intervals, (a, b) -> a[0] - b[0]);
9+
10+
// [0], [1] ์„ start, end๋กœ ์„ ์–ธํ•œ๋‹ค.
11+
int start = intervals[0][0];
12+
int end = intervals[0][1];
13+
14+
Map<Integer, Integer> map = new HashMap<>();
15+
16+
for (int i = 0; i < intervals.length; i++) {
17+
int curS = intervals[i][0];
18+
int curE = intervals[i][1];
19+
20+
if(curS <= end) {
21+
end = Math.max(curE, end);
22+
} else {
23+
start = curS;
24+
end = curE;
25+
}
26+
27+
// {1,3} , {1,6}์ด ์ฐจ๋ก€๋กœ ๋“ค์–ด์™”์„ ๋•Œ ๋” ๋‚˜์ค‘์— ๋“ค์–ด์˜จ ๊ฐ’์œผ๋กœ overlapp ๋  ๊ฒƒ์ด๋ผ๋Š” ์ ์„ ์ด์šฉํ–ˆ๋‹ค.
28+
map.put(start, end);
29+
}
30+
31+
int[][] answer = new int[map.size()][2];
32+
33+
int idx = 0;
34+
for(Map.Entry<Integer, Integer> entry : map.entrySet()) {
35+
int[] item = new int[]{entry.getKey(), entry.getValue()};
36+
answer[idx] = item;
37+
idx++;
38+
}
39+
40+
return answer;
41+
}
42+
}

0 commit comments

Comments
ย (0)