我有一段代码,用于搜索已排序数组并返回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;
}
在什么情况下应该使用“左侧小于或等于右侧”,或只使用“左侧小于右侧”?
if
语句。@MattTimmermans - user2736738