[LeetCode] 240. Search a 2D Matrix Ⅱ(矩阵搜索之二)
-
Difficulty: Medium
-
Related Topics: Binary Search, Divide and Conquer
Description
Write an efficient algorithm that searches for a target
value in an m x n
integer matrix
. The matrix
has the following properties:
设计一个高效算法,判断一个给定值 target
是否存在于给定的 m x n
整数矩阵 matrix
中。matrix
具有以下属性:
- Integers in each row are sorted in ascending from left to right.
每一行上的整数从左到右升序排序。 - Integers in each column are sorted in ascending from top to bottom.
每一列上的整数从上到下升序排序。
Examples
Example 1
Input: 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
Output: true
Example 2
Input: 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 = 20
Output: false
Constraints
m == matrix.length
n == matrix[i].length
1 <= n, m <= 300
-1e9 <= matix[i][j] <= 1e9
- All the integers in each row are sorted in ascending order.
- All the integers in each column are sorted in ascending order.
-1e9 <= target <= 1e9
Solution
这题的关键点在于初始点的选取,一开始我傻乎乎地把起始点放在正中心,结果发现怎么搜也搜不了。discussion 里给出的一个解法是以左上角作为起始点:
-
若目标值比当前值大,说明目标值不在当前值所在的这一行
-
若目标值比当前值小,说明目标值不在当前值所在的这一列
代码如下:
class Solution {
fun searchMatrix(matrix: Array<IntArray>, target: Int): Boolean {
if (matrix.isEmpty() || matrix[0].isEmpty()) {
return false
}
var row = 0
var col = matrix[0].lastIndex
while (row < matrix.size && col >= 0) {
val curValue = matrix[row][col]
if (target == curValue) {
return true
} else if (target > curValue) {
row++
} else {
col--
}
}
return false
}
}