【发布时间】:2016-02-11 19:54:33
【问题描述】:
编辑:
对于二维数组,仅对列进行了排序,但未对行进行排序。下面是我写的方法,首先对每一列进行二进制搜索,然后遍历每一列并计算重复元素。但是代码对我不起作用。有人可以帮助我吗?非常感谢!
public static int count(int[][] array, int query) {
int count = 0;
for (int j = 0; j < array[0].length; j++) {
count += biSearch(array, query, j);
}
return count;
}
private static int biSearch(int[][] array, int searchItem, int row) {
// create a 1D array to hold the entries of 2D array's column
int[] column = new int[array.length];
int count = 0;
int low = 0;
int high = column.length - 1;
// put 2D array's column into 1D array
for (int i = 0; i < array.length; i++)
column[i] = array[i][row];
// binary search on column array
while (low < high) {
int mid = (low + high) / 2;
if ( column[mid]== searchItem ) {
while ((mid - 1) >= 0) {
if (column[mid - 1] == searchItem){
mid--;
count++;
}
}
while ((mid + 1) < (column.length - 1)) {
if (column[mid + 1] == searchItem){
mid++;
count++;
}
}
}
else if ( column[mid] > searchItem)
high = mid - 1;
else if (column[mid] <searchItem )
low = mid + 1;
}
return count;
}
【问题讨论】:
-
你的意思是它不起作用?你有错误吗?输出错误?某些输入的输出错误?
-
@Michal Frystacky 运行时,二进制搜索方法看起来根本不起作用。我猜二维数组元素到一维数组元素的转换是错误的。谢谢。
标签: java binary-search