LeetCode83|排序矩阵查找

时间:2022-07-26
本文章向大家介绍LeetCode83|排序矩阵查找,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

1,问题简述

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

2,示例

示例:

现有矩阵 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。

3,题解思路

正常的题解思路

4,题解程序


public class SearchMatrixTest2 {
    public static void main(String[] args) {
        int[][] 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}
        };
        int target = 5;
        boolean searchMatrix = searchMatrix(matrix, target);
        System.out.println("searchMatrix = " + searchMatrix);
    }

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

5,题解程序图片版

6,总结

写这道题时,自己还是有点想快点写的感觉,总是想着赶紧写完,但是过犹不及,还是老老实实写吧,这样自己的内心还是比较平静,毕竟我们没有必要以体量或者方法来说一个人优秀或者不优秀,其实没啥意思,跟过去的自己比较,有所增进就可以了,这样就对的起自己,其实我们周围值得学习和事物太多了,学是学不玩的,题也不是做不完的,所以还是那句话,跟着自己的脚步慢慢走吧,这样当你在回忆自己的成长时也是一件满开心的事情嘛,人生的意义在于你勇敢去追自己喜欢的事情,而不是每个事物都要去追求,也不好说,如果你喜欢每件事情的话,自己斟酌吧