/
240.搜索二维矩阵-ii.java
58 lines (56 loc) · 1.37 KB
/
240.搜索二维矩阵-ii.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
/*
* @lc app=leetcode.cn id=240 lang=java
*
* [240] 搜索二维矩阵 II
*
* https://leetcode-cn.com/problems/search-a-2d-matrix-ii/description/
*
* algorithms
* Medium (39.62%)
* Likes: 276
* Dislikes: 0
* Total Accepted: 51.9K
* Total Submissions: 129.6K
* Testcase Example: '[[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]]\n' +
'5'
*
* 编写一个高效的算法来搜索 m x n 矩阵 matrix 中的一个目标值 target。该矩阵具有以下特性:
*
*
* 每行的元素从左到右升序排列。
* 每列的元素从上到下升序排列。
*
*
* 示例:
*
* 现有矩阵 matrix 如下:
*
* [
* [1, 4, 7, 11, 15],
* [2, 5, 8, 12, 19],
* [3, 6, 9, 16, 22],
* [10, 13, 14, 17, 24],
* [18, 21, 23, 26, 30]
* ]
*
*
* 给定 target = 5,返回 true。
*
* 给定 target = 20,返回 false。
*
*/
// @lc code=start
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
if (matrix.length == 0 || matrix[0].length == 0) return false;
int m = matrix.length, n = matrix[0].length;
int r = 0, c = n - 1;
while (r < m && c >= 0) {
if (matrix[r][c] == target) return true;
else if (matrix[r][c] < target) r++;
else c--;
}
return false;
}
}
// @lc code=end