问题描述:矩阵每一行有序,每一行的最后一个元素小于下一行的第一个元素,查找。
算法分析:这样的矩阵其实就是一个有序序列,可以使用折半查找算法。
public class SearchInSortedMatrix { public static boolean searchMatrix(int[][] matrix, int target) { int m = matrix.length; int n = matrix[0].length; int low = 0; int high = m*n - 1; while(low <= high) { int mid = (low + high)/2; int row = mid / n; int column = mid % n; if(matrix[row][column] == target) { return true; } else if(matrix[row][column] < target) { low = mid + 1; } else { high = mid - 1; } } return false; } }
问题描述:二维矩阵行有序,列有序,进行查找。
算法分析:有两种方法,一种是将矩阵按中心点分成左上,左下,右上,右下,四部分,进行递归查找。
还有一种比较巧妙的查找方法,就是从左下角或者右上角的元素进行查找。
//矩阵每一行有序,每一列有序 public boolean searchMatrix2(int[][] matrix, int target) { int m = matrix.length; int n = matrix[0].length; return helper(matrix, 0, m-1, 0, n-1, target); } public boolean helper(int[][] matrix, int rowStart, int rowEnd, int colStart, int colEnd, int target) { int rm = (rowStart + rowEnd)/2; int cm = (colStart + colEnd)/2; if(rowStart > rowEnd || colStart > colEnd) { return false; } if(matrix[rm][cm] == target) { return true; } else if(matrix[rm][cm] > target) { return helper(matrix, rowStart, rm - 1, colStart, cm - 1, target) || helper(matrix, rm, rowEnd, colStart, cm - 1, target) || helper(matrix, rowStart, rm - 1, cm, colEnd, target); } else { return helper(matrix, rm + 1, rowEnd, cm + 1, colEnd, target) || helper(matrix, rm + 1, rowEnd, colStart, cm, target) || helper(matrix, rowStart, rm, cm + 1, colEnd, target); } } //从右上角元素进行查找 public boolean searchMatrix3(int[][] matrix, int target) { int m = matrix.length; int n = matrix[0].length; int low = 0; int high = m*n - 1; while(low <= high) { int mid = (low + high)/2; int row = mid / n; int column = mid % n; if(matrix[row][column] == target) { return true; } else if(matrix[row][column] < target) { low = mid + 1; } else { high = mid - 1; } } return false; }