leetcode 240-Search a 2D Matrix II(medium)

Posted yshi12

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode 240-Search a 2D Matrix II(medium)相关的知识,希望对你有一定的参考价值。

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.

start from right top:

1. target less than the number, col--;(exclude this column)

2. target larger than the number, row++;(exclude this row)

3. target equals the number

class Solution {
    public boolean searchMatrix(int[][] matrix, int target) {
        int a=matrix.length;
        if(a==0) return false;
        int b=matrix[0].length;
        if(b==0) return false;
        int col=b-1;
        int row=0;
        while(col>=0&&row<a){
            if(target==matrix[row][col]) return true;
            else if(target<matrix[row][col]) col--;
            else row++;
        }
        return false;
    }
}

注意:不要忘了matrix为空 matrix.length==0 or matrix[0].length==0 的corner case!!

以上是关于leetcode 240-Search a 2D Matrix II(medium)的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode240:Search a 2D Matrix II

LeetCode240. Search a 2D Matrix II

LeetCode240. Search a 2D Matrix II

leetcode No240. Search a 2D Matrix II

[二分搜索] leetcode 240 Search a 2D Matrix II

leetcode 240-Search a 2D Matrix II(medium)