LeetCode-面试题 10.09. 排序矩阵查找

题目

给定M×N矩阵,每一行、每一列都按升序排列,请编写代码找出某元素。

示例:

现有矩阵 matrix 如下:
[
[1, 4, 7, 11, 15],
[2, 5, 8, 12, 19],
[3, 6, 9, 16, 22],
[10, 13, 14, 17, 24],
[18, 21, 23, 26, 30]
]

给定target = 5,返回 true
给定 target = 20,返回 false

解题思路

每一行、每一列都按升序排列,所以可从右上角开始遍历,大于目标数,前移一列,小于目标值,下移一行,直到找到或者遍历完所有的元素结束。

代码

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

        if(matrix.length == 0){
            return false;
        }
        int rows = matrix.length;
        int cols = matrix[0].length;
        int i = 0,j = cols-1;
        while(i>=0&&i<rows && j>=0&&j<cols){
            if(matrix[i][j] == target){
                return true;
            }else if(matrix[i][j] < target){
                ++i;
            }else{
                --j;
            }
        }
        return false;

    }
}

效率

image

发布了157 篇原创文章 · 获赞 1 · 访问量 2675

猜你喜欢

转载自blog.csdn.net/qq_34449717/article/details/105459155