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.
The same with Lintcode:
O(M+N) time and O(1) Space
1 public class Solution { 2 public boolean searchMatrix(int[][] matrix, int target) { 3 int m = matrix.length; 4 int n = matrix[0].length; 5 if (matrix==null || m==0 || n==0) return false; 6 int i=0, j=n-1; 7 while (i=0) { 8 if (matrix[i][j] == target) return true; 9 else if (matrix[i][j] > target) {10 j--;11 }12 else i++;13 }14 return false;15 }16 }
Follow Up: 还有没有什么优化
四分法:我先说了下四分法的想法。先和左上角矩形的右下角比,如果比它大就搜三个的矩阵,否则搜另外三个矩阵。
T(N)= 3T(N/4) + O(1)
(nm)^(log_{4}^{3})
她接着问有啥别的优化。我问她有没有可能多次询问,有可能的话用一个hash来存下以前的所有解,方便重复询问时直接判断。但是这样空间复杂度有提升。(时间优化的时候,尽量想用空间换时间)
mem:O(1) -> O(t)
她想要的优化是对于一个矩阵的最后一行做二分搜索后,删掉前几列和最后一行,得到一个子矩阵。重复这样的操作,时间复杂度是O(min(m,n)log(max(m,n)))。之后跟她提了一下这个方法在m和n相差比较大的时候可能比较有用。