• leetcode240- Search a 2D Matrix II- medium


    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.

    For example,

    Consider the following 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]
    ]
    

    Given target = 5, return true.

    Given target = 20, return false.

    1.分治法(TLE了)O(mn)。从左上角出发。利用好如果这个点都不是target了,那目标肯定不会出现在右下角这个性质及时停止搜索止损。如果当前点大了,那肯定没希望了;如果当前点就是目标,那已经成功了;如果当前点小了,分治,向右或者向下找,拆成两个子问题。因

    2.行走法 O(m + n)。从右上角出发。利用好如果当前点大了,这列向下都不可能了,向左走;如果当前点小了,这行向左都不可能了,向下走这个性质。用好性质不一定最差情况要走遍所有格子,走一条路径即可。

    实现1:

    class Solution {
        public boolean searchMatrix(int[][] matrix, int target) {
            if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
                return false;
            }
            return helper(matrix, target, 0, 0);
        }
        
        private boolean helper(int[][] matrix, int target, int x, int y) {
            if ( x >= matrix.length || y >= matrix[0].length || matrix[x][y] > target ) {
                return false;
            }
            if (matrix[x][y] == target) {
                return true;
            }
            if (helper(matrix, target, x + 1, y) || helper(matrix, target, x, y + 1)) {
                return true;
            }
            return false;
        }
    }

    实现2:

    class Solution {
        public boolean searchMatrix(int[][] matrix, int target) {
            if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
                return false;
            }
            int x = 0;
            int y = matrix[0].length - 1;
            while (isInBound(matrix, x, y) && matrix[x][y] != target) {
                if (matrix[x][y] > target) {
                    y--;
                } else {
                    x++;
                }
            }
            if (isInBound(matrix, x, y)) {
                return true;
            }
            return false;
        }
        private boolean isInBound(int[][] matrix, int x, int y) {
            return x >= 0 && x < matrix.length && y >= 0 && y < matrix[0].length;
        }
    }
  • 相关阅读:
    02-Node.js学习笔记-系统模块fs文件操作
    01-Node.js学习笔记-模块成员的导出导入
    Dom对象与jQuery对象的互转
    JDBC02----JDBC执行CURD操作
    JDBC00-----学习说明
    JDBC01-----JDBC的基本使用
    spring16-----XML命名空间和Spring配置文件中的头
    30 . (Java)面向对象编程六大基本原则
    spring15----AOP之通知顺序
    spring14-----AOP之通知参数
  • 原文地址:https://www.cnblogs.com/jasminemzy/p/7977055.html
Copyright © 2020-2023  润新知