首页 > 代码库 > Search a 2D Matrix <leetcode>

Search a 2D Matrix <leetcode>

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.

 

 

思路:首先遍历每一行的首元素,找到目标如果存在,应该在哪一行,然后在行里进行搜索,本来在这里想用二分查找,但是直接扫了一遍也ac了,代码如下(没有进行优化):

 

 1 class Solution { 2 public: 3     bool searchMatrix(vector<vector<int> > &matrix, int target) { 4         int index=0; 5         if(matrix.size()==0) 6         { 7             return false; 8         } 9         if(matrix.size()==1)10         {11             for(int i=0;i<matrix[0].size();i++)12             {13                 if(target==matrix[0][i])14                 {15                     return true;16                 }17             }18             return false;19         }20         for(int i=0;i<matrix.size();i++)21         {22             if(target>matrix[i][0])23             {24                 index++;25             }26             else if(target==matrix[i][0])27             {28                 return true;29             }30         }31         if(index==0)  return false;32         for(int i=0;i<matrix[0].size();i++)33         {34             if(target==matrix[index-1][i])35             {36                 return true;37             }38         }39         return false;40         41     }42 };

 

Search a 2D Matrix <leetcode>