【发布时间】:2015-10-09 02:19:16
【问题描述】:
我试图通过重置高变量来扩展函数以通过二进制搜索查找整数匹配的数量,但它陷入了循环。我猜一种解决方法是复制这个函数来获取最后一个索引来确定匹配的数量,但我认为这不是一个优雅的解决方案。
从这里:
public static Matches findMatches(int[] values, int query) {
int firstMatchIndex = -1;
int lastMatchIndex = -1;
int numberOfMatches = 0;
int low = 0;
int mid = 0;
int high = values[values.length - 1];
boolean searchFirst = false;
while (low <= high){
mid = (low + high)/2;
if (values[mid] == query && firstMatchIndex == -1){
firstMatchIndex = mid;
if (searchFirst){
high = mid - 1;
searchFirst = false;
} else {
low = mid + 1;
}
} else if (query < values[mid]){
high = mid - 1;
} else {
low = mid + 1;
}
}
if (firstMatchIndex != -1) { // First match index is set
return new Matches(firstMatchIndex, numberOfMatches);
}
else { // First match index is not set
return new Matches(-1, 0);
}
}
到这样的事情:
public static Matches findMatches(int[] values, int query) {
int firstMatchIndex = -1;
int lastMatchIndex = -1;
int numberOfMatches = 0;
int low = 0;
int mid = 0;
int high = values[values.length - 1];
boolean searchFirst = false;
while (low <= high){
mid = (low + high)/2;
if (values[mid] == query && firstMatchIndex == -1){
firstMatchIndex = mid;
if (searchFirst){
high = values[values.length - 1]; // This is stuck in a loop
searchFirst = false;
}
} else if (values[mid] == query && lastMatchIndex == -1){
lastMatchIndex = mid;
if (!searchFirst){
high = mid - 1;
} else {
low = mid + 1;
}
} else if (query < values[mid]){
high = mid - 1;
} else {
low = mid + 1;
}
}
if (firstMatchIndex != -1) { // First match index is set
return new Matches(firstMatchIndex, numberOfMatches);
}
else { // First match index is not set
return new Matches(-1, 0);
}
}
【问题讨论】:
-
如何使用二分查找来查找给定数字的索引?假设如果找不到值则返回-1,您可以使用该索引来查找重复项的数量吗?例如。二进制搜索在搜索数字“9”时返回索引 5,所以我会在索引 5 的左右搜索重复项,一旦没有重复项就停止。匹配数将为
rightIndex - leftIndex + 1,因为值数组已排序。
标签: java binary-search sorted