|
| 1 | +# 74. 搜索二维矩阵 |
| 2 | + |
| 3 | +[url](https://leetcode-cn.com/problems/search-a-2d-matrix/) |
| 4 | + |
| 5 | +## 题目 |
| 6 | + |
| 7 | +编写一个高效的算法来判断 m x n 矩阵中,是否存在一个目标值。该矩阵具有如下特性: |
| 8 | + |
| 9 | +- 每行中的整数从左到右按升序排列。 |
| 10 | +- 每行的第一个整数大于前一行的最后一个整数。 |
| 11 | + |
| 12 | + |
| 13 | + |
| 14 | +``` |
| 15 | +输入:matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3 |
| 16 | +输出:true |
| 17 | +``` |
| 18 | + |
| 19 | + |
| 20 | + |
| 21 | +``` |
| 22 | +输入:matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13 |
| 23 | +输出:false |
| 24 | +``` |
| 25 | + |
| 26 | + |
| 27 | + |
| 28 | +## 方法 |
| 29 | + |
| 30 | + |
| 31 | + |
| 32 | + |
| 33 | +## code |
| 34 | + |
| 35 | +### js |
| 36 | + |
| 37 | +```js |
| 38 | +let searchMatrix = (matrix, target) => { |
| 39 | + if (matrix === null || matrix.length === 0 || matrix[0].length === 0) return false; |
| 40 | + let rows = matrix.length, cols = matrix[0].length; |
| 41 | + let c = cols - 1, r = 0; |
| 42 | + while (c >= 0 && r < rows) { |
| 43 | + if (matrix[r][c] === target) |
| 44 | + return true; |
| 45 | + else if (matrix[r][c] < target) |
| 46 | + r++; |
| 47 | + else |
| 48 | + c--; |
| 49 | + } |
| 50 | + return false |
| 51 | +} |
| 52 | +``` |
| 53 | + |
| 54 | +### go |
| 55 | + |
| 56 | +```go |
| 57 | +func searchMatrix(matrix [][]int, target int) bool { |
| 58 | + if len(matrix) == 0 || len(matrix[0]) == 0 { |
| 59 | + return false |
| 60 | + } |
| 61 | + rows, cols := len(matrix), len(matrix[0]) |
| 62 | + c, r := cols - 1, 0 |
| 63 | + for c >= 0 && r < rows { |
| 64 | + if matrix[r][c] == target { |
| 65 | + return true |
| 66 | + } else if matrix[r][c] < target { |
| 67 | + r++ |
| 68 | + } else { |
| 69 | + c-- |
| 70 | + } |
| 71 | + } |
| 72 | + return false |
| 73 | +} |
| 74 | +``` |
| 75 | + |
| 76 | + |
| 77 | + |
| 78 | +### java |
| 79 | + |
| 80 | +```java |
| 81 | +class Solution { |
| 82 | + public boolean searchMatrix(int[][] matrix, int target) { |
| 83 | + if (matrix == null || matrix.length == 0 || matrix[0].length == 0) |
| 84 | + return false; |
| 85 | + int rows = matrix.length, cols = matrix[0].length; |
| 86 | + int c = cols - 1, r = 0; |
| 87 | + while (c >= 0 && r < rows) { |
| 88 | + if (matrix[r][c] == target) |
| 89 | + return true; |
| 90 | + else if (matrix[r][c] < target) |
| 91 | + r++; |
| 92 | + else |
| 93 | + c--; |
| 94 | + } |
| 95 | + return false; |
| 96 | + } |
| 97 | +} |
| 98 | +``` |
| 99 | + |
0 commit comments