leetcode解题: Search a 2D Matrix II (240)

Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:

Integers in each row are sorted in ascending from left to right.
Integers in each column are sorted in ascending from top to bottom.
For example,

Consider the following matrix:

1
2
3
4
5
6
7
[
[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]
]

Given target = 5, return true.

Given target = 20, return false.

解法1:O(N + M)

这题和Matrix I的区别是上一行和下一行不是递增的,也就是说不能串起来当成一个sorted array来处理。
这题要变换下思路,考虑右上角和左下角两个点。比如左下角,比数字大就往上,比它数字小就往右。直到找到所要求的答案。
Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public 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 x = m - 1;
int y = 0;
while (true) {
if (matrix[x][y] < target) {
++y;
} else if (matrix[x][y] > target) {
--x;
} else {
return true;
}
if (x < 0 || y >= n) {
return false;
}
}
}
}