[C++]LeetCode: 61 Search a 2D Matrix

来源:互联网 发布:网络手机铃声大全试听 编辑:程序博客网 时间:2024/06/06 07:07
题目:

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.

思路:根据题意,矩阵每行都有序排列,并且逐行增加,所以我们可以把MN矩阵展开成一维有序数组。

num表示元素的序列号,从0开始。i, j表示矩阵中的行列坐标,从0开始。
Num = n*i + j;  => i = Num /n ; j = Num % n; n表示矩阵的列。(画图可以得到)

接下来利用二分查找,找到target.

Attention: 注意将矩阵中的序列号和矩阵行列号的转换。

 int mid = lo + (hi - lo) /2; int i = mid / n; int j = mid % n;

复杂度:O(log(N)) 

AC Code: (MY_CODE ONE_PASS)

class Solution {public:    bool searchMatrix(vector<vector<int> > &matrix, int target) {        //其实类似于将mn矩阵展开成一个数组然后查找,不过需要根据第几个元素,计算行列        //num表示元素的序列号,从0开始。i,j表示矩阵中的行列坐标,从0开始。        //Num = n*i + j;  => i = Num /n ; j = Num % n; n表示矩阵的列。                bool ret = false;        if(matrix.size() == 0 || matrix[0].size() == 0) return ret;        int m = matrix.size();        int n = matrix[0].size();                int lo = 0;        int hi = (m - 1) * n + (n - 1);  // hi = m * n -1;                while(lo <= hi)        {            int mid = lo + (hi - lo) /2;            int i = mid / n;            int j = mid % n;            if(target > matrix[i][j])            {                lo = mid + 1;            }            else if(target < matrix[i][j])            {                hi = mid - 1;            }            else            {               ret = true;               break;            }        }                return ret;        }};


0 0