zoukankan      html  css  js  c++  java
  • 【LeetCode-数组】搜索二维矩阵 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。
    

    思路

    《剑指Offer》原题。从右上角或者左下角开始搜索。假设从右上角 matrix[r][c]开始搜索:

    • 如果 r<rows && c >=0:
      • 如果当前元素等于 target,则返回 true;
      • 如果当前元素大于 target,则右移一步;
      • 如果当前元素小于 target,则下移一步;
    • 返回 false;

    代码如下:

    class Solution {
    public:
        bool searchMatrix(vector<vector<int>>& matrix, int target) {
            if(matrix.empty()) return 0; // 防止输入是 [[]]
            int rows = matrix.size();
            int cols = matrix[0].size();
            if(rows==0 || cols==0) return false;   //防止输入是 [[1]]
    
            int r = 0;
            int c = cols-1;
            while(r<rows && c>=0){
                if(matrix[r][c]==target) return true;
                if(matrix[r][c]>target) c--;
                else if(matrix[r][c]<target) r++;
            }
            return false;
        }
    };
    
    • 时间复杂度:O(rows*cols)
    • 空间复杂度:O(1)
  • 相关阅读:
    C#动态显示时间
    死锁问题
    TCP_NODELAY算法使用事项
    二叉搜索树的后序遍历
    从上到下打印二叉树
    栈的压入、弹出序列
    包含min函数的栈
    顺时针打印矩阵
    树的子结构
    合并两个排序链表
  • 原文地址:https://www.cnblogs.com/flix/p/13155298.html
Copyright © 2011-2022 走看看