zoukankan      html  css  js  c++  java
  • 【leetcode】Search a 2D Matrix

    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        
     5         int row=matrix.size();
     6         int col=matrix[0].size();
     7         vector<int> m(row*col);
     8        
     9         for(int i=0;i<row;i++)
    10         {
    11             for(int j=0;j<col;j++)
    12             {
    13                 m[i*col+j]=matrix[i][j];
    14             }
    15         }
    16        
    17         int left=0;
    18         int right=m.size()-1;
    19         int mid;
    20         while(left<=right)
    21         {
    22             mid=(left+right)/2;
    23             if(m[mid]>target)
    24                 right=mid-1;
    25             else if(m[mid]<target)
    26                 left=mid+1;
    27             else
    28                 return true;
    29         }
    30         return false;
    31        
    32     }
    33 };
     
     
    第二种思路,直接使用二分法
     
    把一维数字转化为二维的坐标的方法:
    第n个元素,在n/col行,n%col列
     
     1 class Solution {
     2 public:
     3     bool searchMatrix(vector<vector<int> > &matrix, int target) {
     4        
     5         int row=matrix.size();
     6         int col=matrix[0].size();
     7        
     8         int left=0;
     9         int right=row*col-1;
    10         int mid;
    11         int m;
    12         while(left<=right)
    13         {
    14             mid=(left+right)/2;
    15             m=matrix[mid/col][mid%col];
    16             if(m>target)
    17                 right=mid-1;
    18             else if(m<target)
    19                 left=mid+1;
    20             else
    21                 return true;
    22         }
    23         return false;          
    24     }
    25 };
  • 相关阅读:
    linux kgdb 补丁
    linux kdb 内核调试器
    linux 使用 gdb
    linux 系统挂起
    linux oops 消息
    linux strace 命令
    linux ioctl 方法
    linux seq_file 接口
    [数据结构] 迷宫问题(栈和队列,深搜和广搜)
    简化浏览器地址栏訪问路径
  • 原文地址:https://www.cnblogs.com/reachteam/p/4251644.html
Copyright © 2011-2022 走看看