• 搜索二维矩阵 II


    描述:  

    编写一个高效的算法来搜索 m x n 矩阵 matrix 中的一个目标值 target。该矩阵具有以下特性:
        • 每行的元素从左到右升序排列。
        • 每列的元素从上到下升序排列。

    示例:

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

    思路:

    这道题本质上就是遍历二维数组,我们可以直接遍历,但是由于数组中的数据是存在规律的(下大于上、右大于左),所以我们可以根据其规律,对其进行类似于“剪枝”的操作。

    这里我们是从左下角开始遍历的,即示例中的18。这样遍历的好处是,比18大的元素,都在其右侧,比18小的元素,都在其上方。

    如果从1开始遍历,无论是下方元素,还是右侧元素,都是大于1的。需要额外进行比较(比较下方和右侧元素和target的大小)。

    java

    class Solution {
        public boolean searchMatrix(int[][] matrix, int target) {
            // check
            if (matrix == null || matrix.length == 0) {
                return false;
            }
            if (matrix[0] == null || matrix[0].length == 0) {
                return false;
            }
            // 确定边界
            int bottom = matrix.length - 1;
            int right = matrix[0].length - 1;
            // 确定起点
            int i = bottom, j = 0;
            while (i >= 0 && j <= right) {
                if (matrix[i][j] > target) {
                    i--;
                } else if (matrix[i][j] < target) {
                    j++;
                } else {
                    return true;
                }
            }
            return false;
        }
    }

    结果:

     

    python3:

    class Solution:
        def searchMatrix(self, matrix, target):
            # check
            if not matrix and len(matrix) == 0:
                return False
            if not matrix[0] and len(matrix[0]) == 0:
                return False
            # 确定边界
            bottom, right = len(matrix) - 1, len(matrix[0]) - 1
            i, j = bottom, 0
            while i >= 0 and j <= right:
                if matrix[i][j] > target:
                    i -= 1
                elif matrix[i][j] < target:
                    j += 1
                else:
                    return True
            return False

    结果:

  • 相关阅读:
    Spring事务管理学习笔记
    写给初学前端工程师的一封信
    angularjs 自定义指令弹窗
    ng-if和ng-show的区别
    前端遇到的一些坑
    浏览器样式兼容总结
    百分比控制表格列宽,不起效
    ng-model 将时间戳转换为标准时间
    使用git和sourcetree提交代码的一些问题
    本地运行angularjs应用,提示出现跨域问题
  • 原文地址:https://www.cnblogs.com/nedulee/p/11957804.html
Copyright © 2020-2023  润新知