-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy path14.2.swift
63 lines (46 loc) · 1.62 KB
/
14.2.swift
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
58
59
60
61
62
63
public func solution(inout A : [Int], inout _ B : [Int], inout _ C : [Int]) -> Int {
// write your code in Swift 2.2 (Linux)
func buildCumulativeNails(nailed: [Bool]) -> [Int] {
var cumulativeNails = Array(count: nailed.count, repeatedValue: 0)
var nails = 0
for i in 0..<cumulativeNails.count {
if nailed[i] {
nails += 1
}
cumulativeNails[i] = nails
}
return cumulativeNails
}
func buildNailed(c: [Int], cIndexLimit: Int) -> [Bool] {
var nailed = Array(count: 2 * C.count + 1, repeatedValue: false)
for i in 0..<cIndexLimit {
nailed[c[i]] = true
}
return nailed
}
func hasAnyNailBetween(cumulativeNails: [Int], begin: Int, end: Int) -> Bool {
return (cumulativeNails[end] - (begin == 0 ? 0 : cumulativeNails[begin - 1])) > 0
}
func coverAll(a: [Int], b: [Int], c: [Int], cIndexLimit: Int) -> Bool {
let cumulativeNails = buildCumulativeNails(buildNailed(c, cIndexLimit: cIndexLimit))
for i in 0..<a.count {
if !hasAnyNailBetween(cumulativeNails, begin: A[i], end: B[i]) {
return false
}
}
return true
}
var minNailNum = -1
var lower = 0
var upper = C.count
while lower <= upper {
let middle = (lower + upper) / 2
if coverAll(A, b: B, c: C, cIndexLimit: middle) {
minNailNum = middle
upper = middle - 1
} else {
lower = middle + 1
}
}
return minNailNum
}