-
Notifications
You must be signed in to change notification settings - Fork 3
/
NailingPlanks.java
64 lines (50 loc) · 1.7 KB
/
NailingPlanks.java
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
64
/*
Count the minimum number of nails that allow a series of planks to be nailed.
*/
import java.util.*;
class Solution {
public int solution(int[] A, int[] B, int[] C) {
int[][] nails = new int[C.length][2];
for (int i = 0; i < C.length; i++) {
nails[i][0] = C[i];
nails[i][1] = i;
}
Arrays.sort(nails, (nail1, nail2) -> {
return nail1[0] - nail2[0];
});
int J = 0;
for (int i = 0; i < A.length; i++) {
int start = A[i];
int end = B[i];
int bestIndex = findBestNail(start, end, nails, J);
if (bestIndex == -1) return -1;
J = Math.max(J, bestIndex);
}
return J + 1;
}
int findBestNail(int start, int end, int[][] nails, int curResult) {
int low = 0;
int high = nails.length;
int index = -1;
while (low < nails.length && low <= high) {
int mid = low + ((high - low) / 2);
if (nails[mid][0] < start) {
low = mid + 1;
} else if (nails[mid][0] > end) {
high = mid - 1;
} else{
index = mid;
high = mid - 1;
}
}
if (index == -1) return -1;
int bestIndex = nails[index][1];
for (int i = index; i < nails.length; i++) {
int curNailPos = nails[i][0];
if (curNailPos > end) break;
bestIndex = Math.min(bestIndex, nails[i][1]);
if (bestIndex <= curResult) return bestIndex;
}
return bestIndex;
}
}