Skip to content

Commit 4cb328b

Browse files
committed
solve 240.search-a-2-d-matrix-ii
1 parent dcf0fc3 commit 4cb328b

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
/*
2+
* @lc app=leetcode id=240 lang=java
3+
*
4+
* [240] Search a 2D Matrix II
5+
*
6+
* https://leetcode.com/problems/search-a-2d-matrix-ii/description/
7+
*
8+
* algorithms
9+
* Medium (41.27%)
10+
* Likes: 1722
11+
* Dislikes: 50
12+
* Total Accepted: 200.2K
13+
* Total Submissions: 484.8K
14+
* 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]]\n5'
15+
*
16+
* Write an efficient algorithm that searches for a value in an m x n matrix.
17+
* This matrix has the following properties:
18+
*
19+
*
20+
* Integers in each row are sorted in ascending from left to right.
21+
* Integers in each column are sorted in ascending from top to bottom.
22+
*
23+
*
24+
* Example:
25+
*
26+
* Consider the following matrix:
27+
*
28+
*
29+
* [
30+
* ⁠ [1, 4, 7, 11, 15],
31+
* ⁠ [2, 5, 8, 12, 19],
32+
* ⁠ [3, 6, 9, 16, 22],
33+
* ⁠ [10, 13, 14, 17, 24],
34+
* ⁠ [18, 21, 23, 26, 30]
35+
* ]
36+
*
37+
*
38+
* Given target = 5, return true.
39+
*
40+
* Given target = 20, return false.
41+
*
42+
*/
43+
class Solution {
44+
public boolean searchMatrix(int[][] matrix, int target) {
45+
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
46+
return false;
47+
}
48+
49+
int rowMax = matrix.length - 1;
50+
int colMax = matrix[0].length - 1;
51+
int rowCur = 0;
52+
int colCur = colMax;
53+
54+
while (rowCur <= rowMax && colCur >= 0) {
55+
if (matrix[rowCur][colCur] == target) {
56+
return true;
57+
} else if (matrix[rowCur][colCur] > target) {
58+
colCur--;
59+
} else {
60+
rowCur++;
61+
}
62+
}
63+
64+
return false;
65+
}
66+
}
67+

0 commit comments

Comments
 (0)