码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2018-09-23 16:35:55      阅读:140      评论:0      收藏:0      [点我收藏+]

标签:win   medium   public   sort   prope   his   false   rop   efficient   

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)

标签:win   medium   public   sort   prope   his   false   rop   efficient   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!