我有点坚持自己实现2D数组的二进制搜索 . 它似乎没有迭代到下一行并保持在同一列(因此是一个永无止境的循环) . 二进制搜索的工作方式是从两个 endpoints (低 endpoints 和高 endpoints )之间的中间开始 . 如果查询太低,则将高 endpoints 重新调整为中间点 - 1.如果查询过高,则将低 endpoints 设置为中间 endpoints 1.所有这些都发生在查询之前发现,或者没有匹配因此导致O(log n)的最坏情况 . 但是,我似乎无法让数组逐行进行并搜索值 . 这是我到目前为止所做的:
public static int count(int[][]array, int query) {
int countoccurences = 0;
int low = 0;
int high = array[0].length - 1;
for (int row = 0; row < array.length; row++) {
for (int column = 0; column < array[row].length; column++) {
while (low <= high) {
int mid = (low + high) / 2; //Set mid point to be (low + high) divided by 2
if (array[row][mid] == query ) { //Check if middle value in each column is equal to the search query
countoccurences++; //If it is, increment countoccurences by 1
} else if (array[row][mid] < query) {
low = mid + 1; //If it is less than query then re-adjust low to be mid index + 1
} else {
high = mid - 1; //if query is too low, re-adjust high to be mid index - 1
}
}
}
}
return countoccurences;
}
public static void main(String[] args) {
int[][] array = { {7, 4, 3, 5, 10},{8, 5, 4, 6, 11},{10, 10, 8, 10, 13}, {11, 10, 15, 10, 14}};
System.out.println("Total occurences of the number 10 is: " + count(array, 10));
}
}
谢谢!
1 回答
我觉得你需要这样的东西
重要变化:
交换行和列以匹配您的数据的实际排序方向
介绍了
break;
,以了解列中有查询的情况 . 这就是代码中无限循环的原因删除了外部
for (int column = 0; column < array[row].length; column++)
因为没有意义另一方面,
for (int row = low; row <= high; row++)
. 它应涵盖同一行中有多个目标值的情况,例如数据中的第3列 . 这个内部循环也可以使用更有效的二进制搜索,但我太懒了 .