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

    题目:搜索二维矩阵 

    描述:

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

    这个矩阵具有以下特性:

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

    样例

    考虑下列矩阵:

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

    给出 target = 3,返回 true

    -------------------------------------------

    开始用两个二分搜索,先找列,再找行。运行后提示超时。。。

     1 class Solution {
     2 public:
     3     /**
     4      * @param matrix, a list of lists of integers
     5      * @param target, an integer
     6      * @return a boolean, indicate whether matrix contains target
     7      */
     8     bool searchMatrix(vector<vector<int> > &matrix, int target) {
     9         // write your code here
    10         if (matrix.empty()) {
    11             return 0;
    12         }
    13         int i = 0;
    14         int j = matrix[0].size() - 1;
    15         while (i < matrix.size() && j >= 0) {
    16             int curr = matrix[i][j];
    17             if (target == curr) {
    18                 return 1;
    19             } else if (curr < target) {
    20                 i++;
    21             } else {
    22                 j--;
    23             }
    24         }
    25         return 0;
    26     }
    27 };
  • 相关阅读:
    Python列表生成
    Python 多线程
    Python面向对象编程
    map, reduce和filter(函数式编程)
    35个高级python知识点
    python之pyc
    Python之简单的用户名密码验证
    EasyUI 实例
    hibernate映射文件one-to-one元素属性
    Java中多对多映射关系
  • 原文地址:https://www.cnblogs.com/gousheng/p/6659200.html
Copyright © 2011-2022 走看看