【问题标题】:Binary search an element (with duplicate items) in a 2D array column-wise sorted?二进制搜索二维数组中的元素(具有重复项)按列排序?
【发布时间】: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


【解决方案1】:

不确定这是否是唯一的问题,但这段代码是错误的:

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++;
        }
    }
} 

它基本上测试了从mid0 以及从0column.length-1column 数组的所有元素。不仅您传递了整个数组,这违背了二进制搜索的目的,而且您访问了 mid0 之间的所有元素两次,这意味着您的计数是错误的。

更好的方法:

if ( column[mid]== searchItem ) {
    count = 1;
    int temp = mid;
    while (temp > 0 && column[temp - 1] == searchItem) { 
        temp--;
        count++;
    }
    temp = mid;
    while (temp < column.length - 1 && column[temp + 1] == searchItem) {
        temp++;
        count++;
    }
}

需要注意的两点:

  1. 我不修改mid,因为第二个while循环需要mid的原始值。

  2. 当我遇到不等于searchItem 的元素时,我退出了每个while 循环。由于数组应该是排序的(否则二进制搜索将不起作用),因此无需遍历整个数组。

附: biSearch 中名为 row 的参数实际上是二维数组列的索引,因此它的名称令人困惑。

【讨论】:

  • 非常感谢您的回答和建议,我会尝试测试一下。
猜你喜欢
  • 1970-01-01
  • 2012-01-04
  • 1970-01-01
  • 2021-02-03
  • 1970-01-01
  • 2017-09-08
  • 1970-01-01
  • 2021-12-18
  • 2021-12-06
相关资源
最近更新 更多