標籤:int size 遍曆 尋找 str leetcode closed 簡單的 面試題
面試題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 }View Code
【劍指offer】Java實現