首页 > 其他 > 详细

搜索二维矩阵

时间:2019-09-14 10:30:00      阅读:69      评论: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 from left to right.
The first integer of each row is greater than the last integer of the previous row.

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/search-a-2d-matrix
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

 

要求在一个二维矩阵找出目标数。借鉴其中一个题解的做法,从右上角开始遍历,目标数比右上角的数大,证明不在当前一行,行数+1;目标数比右上角的数小,证明不在当前一列,列数-1:

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

 

搜索二维矩阵

原文:https://www.cnblogs.com/WakingShaw/p/11518217.html

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