題目連接:https://leetcode.com/problems/search-a-2d-matrix-ii/description/ide
題目大意:一個矩陣,每行從左到右,數值以升序排列;每列從上到下,數值以升序排列。從這個矩陣中找到是否有target數值存在,若是有返回true,不然返回false。spa
解法一:利用74題的解法一,逐一的對每一行進行二分查找操做。代碼以下(耗時15ms):code
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):blog
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 }