【leetcode】74. Search a 2D Matrix

来源:互联网 发布:java格斗游戏 编辑:程序博客网 时间:2024/06/05 15:22

Difficulty:medium

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.

解题思路(时间复杂度O(log n)):

这道题目其实相对在medium的难度中非常简单的一道题目,就是简单的二分搜索的变形,从一维矩阵便到了二维矩阵,但是这并不影响对二分搜索的使用。

题目中看到每一行的最后一个数字大于下一行的第一个数字,那么就可以看成第i行后顺接第i+1行,这样的话就构成了一维的矩阵。

而在操作时仅仅需要将二维转换成一维的就可以。同一维的计算相类似,设置left,right两个变量分别为0和矩阵的元素总个数-1,然后用left<=right判断循环条件,在计算mid时,需要将mid转化为二维的矩阵中的坐标,x,y

   int x=mid/m;
           int y=mid%m;

这样就可以用来判断matrix[x][y]与target之间的关系了。

其余部分都与一维矩阵的二分搜索相同,不再赘述。

代码如下:

class Solution {public:    bool searchMatrix(vector<vector<int>>& matrix, int target) {       int n=matrix.size();       int m=matrix[0].size();       int left,right;       left=0;       right=n*m-1;       while(left<=right)       {           int mid=(left+right)/2;           int x=mid/m;           int y=mid%m;           if(matrix[x][y]==target) return true;           else if(target>matrix[x][y])           {               left=mid+1;           }           else right=mid-1;       }       return false;    }};


0 0
原创粉丝点击