More:【目錄】LeetCode Java實現html
Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:java
Example 1:post
Input: matrix = [ [1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50] ] target = 3 Output: true
Example 2:ui
Input: matrix = [ [1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50] ] target = 13 Output: false
regard the matrix as an array, and then use binary search.spa
matrix[x][y]=array[x*cols+y]htm
array[m]=matrix[m/cols][m%cols]blog
public boolean searchMatrix(int[][] matrix, int target) { if(matrix==null || matrix.length<=0 || matrix[0].length<=0) return false; int rows=matrix.length; //行數 int cols=matrix[0].length; //列數 int low=0; int high=rows*cols-1; while(low<=high){ int mid=(low+high)/2; if(matrix[mid/cols][mid%cols]==target){ return true; }else if(matrix[mid/cols][mid%cols]>target){ high=mid-1; }else if(matrix[mid/cols][mid%cols]<target){ low=mid+1; } } return false; }
Time complexity : O(log(n*m))
ip
Space complexity : O(1)
ci
1. Ought to have a good command of the change between array <=> matrix, especially the change of their indexesget
More:【目錄】LeetCode Java實現