LeetCode 240. Search a 2D Matrix II
Description:
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.
Example:
Consider the following 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]
]
Given target = 5, return true.
Given target = 20, return false.
分析:
可从二维数组最后一行第一列的数开始与target比较,当
matrix[m][n] > target
时,m减1,表示该行的数都比target大,不用继续比较该行的数;当matrix[m][n] < target
时,n加1,表示该列的数都比target小,不用继续比较该列的数,应比较更大的列;当找到相等的数时,返回true;否则循环结束后返回false。
代码如下:
1 | class Solution { |