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 };
  • 相关阅读:
    git 使用
    使用Xcode 7 beta免费真机调试iOS应用程序
    Java类更改常量后编译不生效
    Spring AOP中pointcut expression表达式解析
    awk
    sed
    Servlet 单例多线程
    iOS 运行时添加属性和方法
    Lucene5学习之使用MMSeg4j分词器
    redis
  • 原文地址:https://www.cnblogs.com/-wang-cheng/p/4948484.html
Copyright © 2011-2022 走看看