zoukankan      html  css  js  c++  java
  • [LeetCode 240.] Search a 2D Matrix II

    LeetCode 240. Search a 2D Matrix II

    一道经典的二维矩阵搜索题。

    题目描述

    Write an efficient algorithm that searches for a target value in an m x n integer matrix. The 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.

    Example 1:

    Input: 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
    Output: true

    Example 2:

    Input: 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 = 20
    Output: false

    Constraints:

    • m == matrix.length
    • n == matrix[i].length
    • 1 <= n, m <= 300
    • -109 <= matix[i][j] <= 109
    • All the integers in each row are sorted in ascending order.
    • All the integers in each column are sorted in ascending order.
    • -109 <= target <= 109

    解题思路

    这道题是典型的减治算法,关键在于这个中间点的选取。
    本题可以选择副对角线上的两个顶点。只要选取的点与target不相等,便可以一次减去一行或者一列的查找,缩小搜索空间。

    参考代码

    /*
     * @lc app=leetcode id=240 lang=cpp
     *
     * [240] Search a 2D Matrix II
     */
    
    // @lc code=start
    class Solution {
    public:
        bool searchMatrix(vector<vector<int>>& matrix, int target) {
            assert(!matrix.empty() && !matrix[0].empty());
            int m = matrix.size(), n = matrix[0].size();
            int i = m - 1, j = 0;
            while (i >= 0 && j < n) {
                if (matrix[i][j] == target) return true;
                if (matrix[i][j] < target) j++;
                else i--;
            }
            return false;
        }
    };
    // @lc code=end
    
  • 相关阅读:
    正则匹配任意字(包括换行符)
    linux终端光标的快捷键操作
    正则向前查找和向后查找
    正则表达式软件Expresso
    JsonP 跨域完全解析
    PHP代码阅读Phpxref
    ubuntu 操作用户名和密码
    curl多线程解释[转]
    php递归创建多级目录
    离散数学 第一章 命题逻辑 11 命题及其表示法
  • 原文地址:https://www.cnblogs.com/zhcpku/p/14480607.html
Copyright © 2011-2022 走看看