使用二进制搜索检查二维数组中是否有元素存在[关闭]。

问题描述 投票:-1回答:1

写一个有效的算法,在一个m×n矩阵中搜索一个值。这个矩阵具有以下特性。

每行的整数从左到右排序.每行的第一个整数大于前一行的最后一个整数。点击查看

java arrays data-structures binary-search
1个回答
0
投票
public boolean searchMatrix(int[][] matrix, int target) {
    if(matrix.length == 0 || matrix[0].length == 0)
        return false;
    int row = binarySearchRow(matrix,0,matrix.length-1,target);
    return binarySearch(matrix,0,matrix[0].length-1,target,row);
   }

private static int binarySearchRow(int arr[][], int l, int r, int x) { 

        if (r >= l) { 
            int mid = l + (r - l) / 2; 

         //check if element is in between first and last element of that row
            if (x >= arr[mid][0] && x <= arr[mid][arr[0].length-1]) 
                return mid; 

         //if not move on to check other halves
            if (arr[mid][0] > x && arr[mid][arr[0].length-1]>x) 
                return binarySearchRow(arr, l, mid - 1, x); 

                 return binarySearchRow(arr, mid + 1, r, x); 
        } 

    return 0;
}
  public boolean binarySearch(...,row){..apply normal bs here..}
© www.soinside.com 2019 - 2024. All rights reserved.