Skip to content

Commit 0e8917c

Browse files
committed
Create 1851-minimum-interval-to-include-each-query.swift
1 parent bdaf365 commit 0e8917c

File tree

1 file changed

+100
-0
lines changed

1 file changed

+100
-0
lines changed
Lines changed: 100 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,100 @@
1+
class Heap {
2+
var heap = [[0]]
3+
4+
var count: Int {
5+
heap.count - 1
6+
}
7+
8+
var first: [Int] {
9+
heap[1]
10+
}
11+
12+
func heapify(_ arr: [[Int]]) {
13+
heap = arr
14+
heap.append(arr[0])
15+
var cur = (heap.count - 1) / 2
16+
while cur > 0 {
17+
var i = cur
18+
while 2 * i < heap.count {
19+
if 2 * i + 1 < heap.count && heap[2 * i + 1][0] < heap[2 * i][0] && heap[i][0] > heap[2 * i + 1][0] {
20+
let tmp = heap[i]
21+
heap[i] = heap[2 * i + 1]
22+
heap[2 * i + 1] = tmp
23+
i = 2 * i + 1
24+
} else if heap[i][0] > heap[2 * i][0] {
25+
let tmp = heap[i]
26+
heap[i] = heap[2 * i]
27+
heap[2 * i] = tmp
28+
i = 2 * i
29+
} else {
30+
break
31+
}
32+
}
33+
cur -= 1
34+
}
35+
}
36+
37+
func push(_ val: [Int]) {
38+
heap.append(val)
39+
var i = heap.count - 1
40+
while i > 1 && heap[i][0] < heap[i / 2][0] {
41+
let tmp = heap[i]
42+
heap[i] = heap[i / 2]
43+
heap[i / 2] = tmp
44+
i = i / 2
45+
}
46+
}
47+
48+
func pop() -> [Int]? {
49+
if heap.count == 1 {
50+
return nil
51+
}
52+
if heap.count == 2 {
53+
return heap.popLast()
54+
}
55+
let res = heap[1]
56+
heap[1] = heap.removeLast()
57+
var i = 1
58+
while 2 * i < heap.count {
59+
if 2 * i + 1 < heap.count && heap[2 * i + 1][0] < heap[2 * i][0] && heap[i][0] > heap[2 * i + 1][0] {
60+
let tmp = heap[i]
61+
heap[i] = heap[2 * i + 1]
62+
heap[2 * i + 1] = tmp
63+
i = 2 * i + 1
64+
} else if heap[i][0] > heap[2 * i][0] {
65+
let tmp = heap[i]
66+
heap[i] = heap[2 * i]
67+
heap[2 * i] = tmp
68+
i = 2 * i
69+
} else {
70+
break
71+
}
72+
}
73+
return res
74+
}
75+
}
76+
77+
class Solution {
78+
func minInterval(_ intervals: [[Int]], _ queries: [Int]) -> [Int] {
79+
var intervals = intervals.sorted(by: { $0[0] < $1[0] })
80+
let minHeap = Heap()
81+
var res = [Int: Int]()
82+
var i = 0
83+
for q in queries.sorted() {
84+
while i < intervals.count && intervals[i][0] <= q {
85+
let l = intervals[i][0]
86+
let r = intervals[i][1]
87+
minHeap.push([r - l + 1, r])
88+
i += 1
89+
}
90+
91+
while minHeap.count > 0 && minHeap.first[1] < q {
92+
minHeap.pop()
93+
}
94+
95+
res[q] = minHeap.count > 0 ? minHeap.first[0] : -1
96+
}
97+
98+
return queries.map { res[$0] ?? -1 }
99+
}
100+
}

0 commit comments

Comments
 (0)