的第一次出现的二进制搜索我有代码,搜索一个排序后的数组,并返回k的第一次出现的索引。 我想知道是否它可以编写使用对于k
while(left<right)
,而不是
while(left<=right)
下面这段代码是全码:
public static int searchFirstOfK(List<Integer> A, int k) {
int left = 0, right = A.size() - 1, result = -1;
// A.subList(left, right + 1) is the candidate set.
while (left <= right) {
int mid = left + ((right - left)/2);
if (A.get(mid) > k) {
right = mid - 1;
} else if (A.get(mid) == k) {
result = mid;
// Nothing to the right of mid can be the first occurrence of k.
right = mid - 1;
} else { // A.get(mid) < k
left = mid + 1;
}
}
return result;
}
我如何知道何时使用左边是小于或等于正确的,或者只是使用左边是不正确的。
为什么当左+ 1 ==右停? –
由于初始化技巧,它根本不需要。 @MattTimmermans我编辑了一下..现在检查 – coderredoc
OIC。这很不错,但是当所有的元素大于或小于你要找的元素时,它就会中断。你需要一个额外的支票 –