题目链接:https://leetcode.com/problems/search-a-2d-matrix-ii/description/
题目大意:一个矩阵,每行从左到右,数值以升序排列;每列从上到下,数值以升序排列。从这个矩阵中找到是否有target数值存在,如果有返回true,否则返回false。
解法一:利用74题的解法一,逐一的对每一行进行二分查找操作。代码如下(耗时15ms):
1 public boolean searchMatrix(int[][] matrix, int target) { 2 if(matrix == null || matrix.length == 0 || matrix[0].length == 0) { 3 return false; 4 } 5 //逐一查找每一行 6 for(int i = 0; i < matrix.length; i++) { 7 //二分查找 8 int low = 0, high = matrix[i].length - 1; 9 while(low <= high) { 10 int mid = (low + high) / 2; 11 if(matrix[i][mid] < target) { 12 low = mid + 1; 13 } 14 else if(matrix[i][mid]> target) { 15 high = mid - 1; 16 } 17 else { 18 return true; 19 } 20 } 21 } 22 return false; 23 }
解法二:巧妙的解法,因为每行每列的数值按照一定顺序排列,当当前值比target小时,则在当前行右移;当当前值比target大时,则在当前列上移,直到找到target或下标越界。代码如下(耗时15ms):
1 public boolean searchMatrix(int[][] matrix, int target) { 2 if(matrix == null || matrix.length == 0 || matrix[0].length == 0) { 3 return false; 4 } 5 int row = matrix.length - 1, col = 0; 6 while(row >= 0 && col < matrix[0].length) { 7 if(matrix[row][col] < target) { 8 col++; 9 } 10 else if(matrix[row][col] > target) { 11 row--; 12 } 13 else { 14 return true; 15 } 16 } 17 return false; 18 }