240. 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.
For 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
.
链接: http://leetcode.com/problems/search-a-2d-matrix-ii/
题解:
在行和列排序好的二维数组中查找目标数字。这里我们用了一个很巧妙的方法,从矩阵的右上角开始找,相当于把这个元素当作mid,目标比mid大,则row + 1,小则col + 1,相等则返回mid。也是类似二分查找的思想。
Time Complexity - O(m + n), Space Complexity - O(1)
public class Solution { public boolean searchMatrix(int[][] matrix, int target) { if(matrix == null || matrix.length == 0) return false; int row = 0, col = matrix[0].length - 1; while (row < matrix.length && col >= 0) { int curElem = matrix[row][col]; if(curElem == target) return true; else if(curElem < target) row++; else col--; } return false; } }
二刷:
方法跟一刷一样。
Java:
Time Complexity - O(m + n), Space Complexity - O(1)
public class Solution { public boolean searchMatrix(int[][] matrix, int target) { if (matrix == null || matrix.length == 0) return false; int rowNum = matrix.length, colNum = matrix[0].length; int i = 0, j = colNum - 1; while (i < rowNum && j >= 0) { if (matrix[i][j] == target) return true; else if (matrix[i][j] < target) i++; else j--; } return false; } }
Reference:
Anany Levitin <Introduction to the Design and Analysis of Algorithms> 3rd edition,4.5, question 13
https://leetcode.com/discuss/47506/ac-clean-java-solution
https://leetcode.com/discuss/48852/my-concise-o-m-n-java-solution
https://leetcode.com/discuss/66657/java-short-code-o-m-n