File tree Expand file tree Collapse file tree 1 file changed +39
-0
lines changed
non-overlapping-intervals Expand file tree Collapse file tree 1 file changed +39
-0
lines changed Original file line number Diff line number Diff line change
1
+ /*
2
+ 풀이
3
+ - 나머지 interval이 overlapping하지 않도록 하기 위해 제거해야 하는 interval의 최소 개수 구하기 문제
4
+ = 서로 overlapping하지 않도록 interval을 담은 배열의 최대 길이 구하기 문제
5
+ - Activity Selection Problem이라는 유형의 문제로 치환할 수 있음 (https://en.wikipedia.org/wiki/Activity_selection_problem)
6
+ - 이 문제의 그리디 증명은 블로그에 정리해두었음 (https://blog.naver.com/sigmapi1000/223532427648?trackingCode=blog_bloghome_searchlist)
7
+ Big O
8
+ - N: intervals의 길이
9
+ - Time complexity: O(NlogN)
10
+ - sort.Slice -> O(NlogN)
11
+ - 두 번째 for문 -> O(N)
12
+ - Space complexity: O(logN)
13
+ - sort.Slice는 퀵소트의 일종을 사용하므로 재귀 호출 스택의 깊이를 고려하여야 함
14
+ */
15
+
16
+ import "sort"
17
+
18
+ func eraseOverlapIntervals (intervals [][]int ) int {
19
+ n := len (intervals )
20
+ if n == 1 {
21
+ return 0
22
+ }
23
+ sort .Slice (intervals , func (i , j int ) bool { // end의 오름차순으로 정렬
24
+ return intervals [i ][1 ] < intervals [j ][1 ]
25
+ })
26
+ res := 0
27
+ prev := 0 // 이전 interval을 가리킴
28
+ curr := 1 // 현재 interval을 가리킴
29
+ for curr < len (intervals ) {
30
+ if intervals [prev ][1 ] > intervals [curr ][0 ] {
31
+ res ++
32
+ curr ++
33
+ } else {
34
+ prev = curr
35
+ curr ++
36
+ }
37
+ }
38
+ return res
39
+ }
You can’t perform that action at this time.
0 commit comments