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 };
  • 相关阅读:
    Linux中的文件特殊权限
    服务器管理
    程序图表统计知识
    EasyUI 添加tab页(iframe方式)
    打造自己的reset.css
    CI的知识点
    easyui资源
    eval解析JSON中的注意点
    如何在一个frame中调用另一个frame中的javascript函数
    Egret 摇一摇功能
  • 原文地址:https://www.cnblogs.com/gousheng/p/6659200.html
Copyright © 2011-2022 走看看