編輯:在二維數組中按二進制搜索元素(具有重複項目)按列順序排序?
對於2D陣列,僅柱進行分選但沒有排序的行。下面是我寫的方法,首先在每列中進行二進制搜索,然後遍歷每一列並計算重複元素。但是代碼對我不起作用。有人可以幫助我嗎?非常感謝!
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運行時,binaray搜索方法看起來根本不起作用,我猜想2D數組元素到1D數組元素的轉換是錯誤的。謝謝。 – Harry