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
    
  • 相关阅读:
    PHP7 快速编译安装
    php访问url的四种方式
    php获取文件 return array数组的值
    thinkphp3.2自定义success及error跳转页面
    think php 访问时
    vtk点云数据的显示[转]
    strlen() 和 sizeof() 在字符串中的使用
    函数 MultiByteToWideChar() 详解
    函数WideCharToMultiByte() 详解
    wchar_t 和 char 之间转换
  • 原文地址:https://www.cnblogs.com/zhcpku/p/14480607.html
Copyright © 2011-2022 走看看