https://leetcode.com/problems/search-a-2d-matrix-ii/

https://discuss.leetcode.com/topic/20064/my-concise-o-m-n-java-solution/2

时间:O(m + n)

public class Solution {

public boolean searchMatrix(int[][] matrix, int target) {

if (matrix == null || matrix.length == 0 || matrix[0].length == 0)

return false;

int row = 0;

int col = matrix[0].length - 1;

while (row < matrix.length && col >= 0) {

if (target == matrix[row][col])

return true;

else if (target > matrix[row][col])

row++;

else

col--;

}

return false;

}

}

*总结:

本质:一直部分有序2D array search target. 行递增列递增下一行头不一定比上一行尾大。所以不能用两次二分先找row的方法了。从右上角开始遍历,target大于它的row+1, target小于它的col-1

results matching ""

    No results matching ""