zoukankan      html  css  js  c++  java
  • LintCode 搜索二维矩阵

    写出一个高效的算法来搜索 m × n矩阵中的值。

    这个矩阵具有以下特性:

    • 每行中的整数从左到右是排序的。
    • 每行的第一个数大于上一行的最后一个整数

    样例

    考虑下列矩阵:

    [
      [1, 3, 5, 7],
      [10, 11, 16, 20],
      [23, 30, 34, 50]
    ]
    

    给出 target = 3,返回 true

    剑指offer 面试题目3 跟这个相仿 :找右上角或者左下角 可以排除一行或一列 效率高

    这个题烦死了 先开始没考虑鲁棒性 后来有数组下表越界

    最后总算通过了。。。

    class Solution {
    public:
        /**
         * @param matrix, a list of lists of integers
         * @param target, an integer
         * @return a boolean, indicate whether matrix contains target
         */
        bool searchMatrix(vector<vector<int> > &matrix, int target) {
            // write your code here
            int found=false;
            if(matrix.empty()|| matrix[0].empty())
               return found;
            if (target < matrix[0][0] || target > matrix.back().back()) 
               return found;  
            int rows=matrix.size();
            int columns=matrix[0].size();
          
              int row=0;
                int column=columns-1;
               while(row < rows && column>=0)
                {
                    if(matrix[row*columns][column]==target)
                    { found=true;
                    break;
                    }
                    else if(matrix[row*columns][column]>target)
                        --column;
                    else
                        ++row;
                }
           
          return found;
        }
    };
    

      

  • 相关阅读:
    mysql外键添加error1215
    shell命令获取最新文件的名称
    centos7 apache提供文件下载
    centos7 时间设置
    微服务通信的类型
    angular-cli
    npm
    模块相关
    加油!冲冲冲
    软件评测
  • 原文地址:https://www.cnblogs.com/lelelelele/p/6099232.html
Copyright © 2011-2022 走看看