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;
    }
};

  

原文地址:https://www.cnblogs.com/lelelelele/p/6099232.html