面试题3 二维数组中的查找 Leetcode--74 Search a 2D Matrix
1 /*Java 2 Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties: 3 4 Integers in each row are sorted from left to right. 5 The first integer of each row is greater than the last integer of the previous row. 6 7 For example, 8 9 Consider the following matrix: 10 11 [ 12 [1, 3, 5, 7], 13 [10, 11, 16, 20], 14 [23, 30, 34, 50] 15 ] 16 17 Given target = 3, return true. 18 本题最简单的方法循环遍历行与列 但是时间复杂度较高。 19 */ 20 class Solution { 21 public boolean searchMatrix(int[][] matrix, int target) { 22 boolean find = false; 23 int rows,cols; 24 if (matrix == null || matrix.length==0) { 25 rows = 0; 26 cols = 0; 27 } else { 28 rows = matrix.length; 29 cols = matrix[0].length; 30 } 31 32 if (matrix != null && rows > 0 && cols > 0) { 33 int row = 0; 34 int col = cols-1; 35 while(row<rows && col>=0){ 36 if(matrix[row][col]==target){ 37 find=true; 38 break; 39 } 40 41 else if(matrix[row][col]>target){ 42 col--; 43 }else{ 44 row++; 45 } 46 } 47 } 48 49 return find; 50 } 51 public static void main(String[] args) { 52 int[][] matrix1 = { { 1, 3, 5, 7 }, { 10, 11, 16, 20 }, { 23, 30, 34, 50 } }; 53 54 int[][] matrix = {}; 55 int target = 55; 56 SearchA2DMatrix cc = new SearchA2DMatrix(); 57 boolean find = cc.searchMatrix(matrix, target); 58 System.out.println(find); 59 } 60 }