zoukankan      html  css  js  c++  java
  • LeetCode OJ:Search a 2D Matrix 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.
    [
      [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进行比较,如果大于target的话那么这一列都不会存在target,小于的话那么改行都不会存在该元素,从而进行下一步的搜寻,代码如下:

     1 class Solution {
     2 public:
     3     bool searchMatrix(vector<vector<int>>& matrix, int target) {
     4         if(!matrix.size() || !matrix[0].size())
     5             return false;
     6         int rowCount = matrix.size();
     7         int colCount = matrix[0].size();
     8         for(int i = 0, j = colCount - 1; i < rowCount && j >= 0; ){
     9             if(matrix[i][j] == target) return true;
    10             else if(matrix[i][j] > target)
    11                 j--;
    12             else
    13                 i++;
    14         } 
    15         return false;
    16     }
    17 };
  • 相关阅读:
    「联赛模拟测试33」题解
    分享几个基于vue的移动端框架
    11-15
    test
    联赛模拟测试20 C. Weed
    联赛模拟测试20 D. Drink
    联赛模拟测试24 联合权值·改
    联赛模拟测试21 表格
    近期的一些考试题目
    shell脚本执行错误 $' ':command not found
  • 原文地址:https://www.cnblogs.com/-wang-cheng/p/4948484.html
Copyright © 2011-2022 走看看