【发布时间】:2020-09-19 20:14:16
【问题描述】:
试图了解 Codility NailingPlanks 的解决方案。
问题链接: https://app.codility.com/programmers/lessons/14-binary_search_algorithm/nailing_planks/
给定两个由 N 个整数组成的非空数组 A 和 B。 这些阵列代表 N 个木板。更准确地说,A[K] 是开始和 B[K] 第 K 个木板的末端。
接下来,给定一个由 M 个整数组成的非空数组 C。这 数组代表 M 个钉子。更准确地说,C[I] 是 你可以敲入第 I 个钉子。
如果存在钉子 C[I],我们说木板 (A[K], B[K]) 被钉了 使得 A[K] ≤ C[I] ≤ B[K]。
目标是找到必须使用的最少钉子数量 直到所有的木板都钉牢。换句话说,你应该找到一个 值 J 使得所有木板都将在仅使用第一个后被钉牢 J钉子。更准确地说,对于每块木板 (A[K], B[K]) 使得 0 ≤ K
解决方案链接: https://github.com/ZRonchy/Codility/blob/master/Lesson12/NailingPlanks.java
import java.util.Arrays;
class Solution {
public int solution(int[] A, int[] B, int[] C) {
// the main algorithm is that getting the minimal index of nails which
// is needed to nail every plank by using the binary search
int N = A.length;
int M = C.length;
// two dimension array to save the original index of array C
int[][] sortedNail = new int[M][2];
for (int i = 0; i < M; i++) {
sortedNail[i][0] = C[i];
sortedNail[i][1] = i;
}
// use the lambda expression to sort two dimension array
Arrays.sort(sortedNail, (int x[], int y[]) -> x[0] - y[0]);
int result = 0;
for (int i = 0; i < N; i++) {//find the earlist position that can nail each plank, and the max value for all planks is the result
result = getMinIndex(A[i], B[i], sortedNail, result);
if (result == -1)
return -1;
}
return result + 1;
}
// for each plank , we can use binary search to get the minimal index of the
// sorted array of nails, and we should check the candidate nails to get the
// minimal index of the original array of nails.
public int getMinIndex(int startPlank, int endPlank, int[][] nail, int preIndex) {
int min = 0;
int max = nail.length - 1;
int minIndex = -1;
while (min <= max) {
int mid = (min + max) / 2;
if (nail[mid][0] < startPlank)
min = mid + 1;
else if (nail[mid][0] > endPlank)
max = mid - 1;
else {
max = mid - 1;
minIndex = mid;
}
}
if (minIndex == -1)
return -1;
int minIndexOrigin = nail[minIndex][1];
//find the smallest original position of nail that can nail the plank
for (int i = minIndex; i < nail.length; i++) {
if (nail[i][0] > endPlank)
break;
minIndexOrigin = Math.min(minIndexOrigin, nail[i][1]);
// we need the maximal index of nails to nail every plank, so the
// smaller index can be omitted ****
if (minIndexOrigin <= preIndex) // ****
return preIndex; // ****
}
return minIndexOrigin;
}
}
我不明白解决方案中标有**** 的第99-102 行。
我的问题是:
如果 minIndexOrigin <= preIndex ,那么它将使用 preIndex,
但是如果preIndex 没有钉住当前的木板怎么办?
解决方案有一点错误吗?
【问题讨论】:
标签: java algorithm binary-search