Search a 2D Matrix
Method One:
Using Binary Search Once. The point is how to calculated the number's index. mtarix[<num> / nCol][<num> % nCol]
public class Solution { /** * @param matrix, a list of lists of integers * @param target, an integer * @return a boolean, indicate whether matrix contains target */ public boolean searchMatrix(int[][] matrix, int target) { // write your code here if (matrix == null || matrix.length == 0) { return false; } if (matrix[0] == null || matrix[0].length == 0) { return false; } int nRow = matrix.length; int nCol = matrix[0].length; int start = 0; int end = nRow * nCol - 1; while (start + 1 < end) { int mid = start + (end - start) / 2; if (matrix[mid / nCol][mid % nCol] == target) { return true; } else if (matrix[mid / nCol][mid % nCol] < target) { start = mid; } else { end = mid; } } if (matrix[start / nCol][start % nCol] == target) { return true; } if (matrix[end / nCol][end % nCol] == target) { return true; } return false; } }
Method Two:
Binary Search Twice
public class Solution { /** * @param matrix, a list of lists of integers * @param target, an integer * @return a boolean, indicate whether matrix contains target */ public boolean searchMatrix(int[][] matrix, int target) { // write your code here if (matrix == null || matrix.length == 0) { return false; } if (matrix[0] == null || matrix[0].length == 0) { return false; } int startRow = 0; int endRow = matrix.length - 1; while (startRow + 1 < endRow) { int mid = startRow + (endRow - startRow) / 2; if (matrix[mid][0] == target) { return true; } else if (matrix[mid][0] < target) { startRow = mid; } else { endRow = mid; } } int row = startRow; if (matrix[startRow][0] == target) { return true; } if(matrix[endRow][0] == target) { return true; } if(matrix[endRow][0] < target ) { row = endRow; } int startCol = 0; int endCol = matrix[row].length - 1; while (startCol + 1 < endCol) { int mid = startCol + (endCol - startCol) / 2; if (matrix[row][mid] == target) { return true; } else if (matrix[row][mid] < target) { startCol = mid; } else { endCol = mid; } } if (matrix[row][startCol] == target) { return true; } if (matrix[row][endCol] == target) { return true; } return false; } }
posted on 2017-05-02 07:44 codingEskimo 阅读(107) 评论(0) 编辑 收藏 举报