zoukankan      html  css  js  c++  java
  • Search a 2D matrix

    题目:

    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 from left to right.
    • The first integer of each row is greater than the last integer of the previous row.

    For example,

    Consider the following matrix:

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

    Given target = 3, return true.

    思路:二分查找,先找到行数再找列数。

    代码:

     1 class Solution {
     2  public:
     3      bool searchMatrix(vector<vector<int> > &matrix, int target) {
     4          // Start typing your C/C++ solution below
     5          // DO NOT write int main() function
     6          int m = matrix.size();
     7          int n = matrix[0].size();
     8          if (matrix[0][0]>target || matrix[m-1][n-1]<target) return false;
     9          int top = 0;
    10          int down = m-1;
    11          int mid;
    12          while (top <= down) {
    13              mid = (top+down)/2;
    14              if (target == matrix[mid][0]) return true;
    15              if (target > matrix[mid][0]) top = mid+1;
    16              else down = mid-1;
    17          }
    18          int row = down;
    19          int left = 0;
    20          int right = n-1;
    21          while (left <= right) {
    22              mid = (left+right)/2;
    23              if (target == matrix[row][mid]) return true;
    24              if (target > matrix[row][mid]) left = mid+1;
    25              else right = mid-1;
    26          }
    27          return false;
    28      }
    29  };
  • 相关阅读:
    oracle数据库数据导出
    oracle 数据连接方式
    plsql 建表空间
    java Excel 导入数据库
    python爬虫学习数据分析(连载中)
    python之pip库管理工具pip安装
    数据结构之看病排队系统
    数据结构之顺序串
    数据结构之链队
    数据结构之环形队列
  • 原文地址:https://www.cnblogs.com/tanghulu321/p/3055787.html
Copyright © 2011-2022 走看看