首页 > 其他 > 详细

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

时间:2018-09-23 16:03:59      阅读:159      评论:0      收藏:0      [点我收藏+]

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)

原文:https://www.cnblogs.com/yshi12/p/9692776.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!