Search a 2D Matrix II
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 | [ |
Given target = 5
, return true
.
Given target = 20
, return false
思路:先试试o(n2)的穷举能不能通过,写了一个竟然通过了
代码如下:
1 | class Solution { |
这道题肯定还有更好的解法,因为我们没有利用它行和列递增的两个属性,仔细观察可以发现,矩阵右上角的元素是当前行的最大值,同时也是当前列的最小值,所以利用这个数和target比较的话,我们每一次都可以至少淘汰一行或者一列。比如,当target大于右上角的数时,我们可以知道,target大于右右上角元素所在的整行,所以可以排除整行;如果target小于右上角元素时,我们可以知道,它小于右上角元素所在的列的所有元素,所以可以排除该列,每次淘汰一行或者1列,所以总的时间复杂度为o(max(m,n));
代码如下:
1 | class Solution { |