zoukankan      html  css  js  c++  java
  • [LeetCode] 240. Search a 2D Matrix II 搜索一个二维矩阵 II

    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.

    74. Search a 2D Matrix 的变形,这题的矩阵特点是:每一行是按从左到右升序排列;每一列从上到下按升序排列。

    解法:有特点的数是左下角和右上角的数。比如左下角的18开始,上面的数比它小,右边的数比它大,和目标数相比较,如果目标数大,就往右搜,如果目标数小,就往上搜。这样就可以判断目标数是否存在。或者从右上角15开始,左面的数比它小,下面的数比它大。

    Python:

    class Solution:
        def searchMatrix(self, matrix, target):
            m = len(matrix)
            if m == 0:
                return False
            
            n = len(matrix[0])
            if n == 0:
                return False
                
            i, j = 0, n - 1
            while i < m and j >= 0:
                if matrix[i][j] == target:
                    return True
                elif matrix[i][j] > target:
                    j -= 1
                else:
                    i += 1
                    
            return False

    C++:

    class Solution {
    public:
        bool searchMatrix(vector<vector<int> > &matrix, int target) {
            if (matrix.empty() || matrix[0].empty()) return false;
            if (target < matrix[0][0] || target > matrix.back().back()) return false;
            int x = matrix.size() - 1, y = 0;
            while (true) {
                if (matrix[x][y] > target) --x;
                else if (matrix[x][y] < target) ++y;
                else return true;
                if (x < 0 || y >= matrix[0].size()) break;
            }
            return false;
        }
    };
    

      

    类似题目:

    [LeetCode] 74. Search a 2D Matrix 搜索一个二维矩阵

    All LeetCode Questions List 题目汇总

  • 相关阅读:
    Mysql 安装
    网站搭建 so easy
    git 命令!!!!!!!!!!!
    git branch 管理常用命令
    Java开发环境的搭建以及使用eclipse从头一步步创建java项目
    git 放弃本地修改 强制更新
    java算法之猴子排序睡眠排序
    sql业务需求,查询每个分类下的前两n条数据
    mysql安装
    linux服务自启
  • 原文地址:https://www.cnblogs.com/lightwindy/p/8628275.html
Copyright © 2011-2022 走看看