LeetCode刷题(C++)——Search a 2D Matrix(Medium)

来源:互联网 发布:开源bug系统 java 编辑:程序博客网 时间:2024/06/04 18:50

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:每次和矩阵的右上角元素进行比较。设右上角元素为y,要查找的元素为x,则

(1)当x<y时,则第一行所有的元素都小于y,可以删掉;

(2)当x>y时,则最后一列所有的元素都大于y,可以删掉;

如此循环比较,直到找到x或者矩阵元素为空。这样每次都能删掉一行或者一列,缩小查找范围。时间复杂度为O(m+n)=O(max(m,n))

代码实现如下:

class Solution {public:    bool searchMatrix(vector<vector<int>>& matrix, int target) {        if(matrix.empty())            return false;        int m = matrix.size(), n = matrix[0].size();        for(int i=0, j=n-1; (i<m)&&(j>=0);){            if(matrix[i][j] == target)                return true;            else if(matrix[i][j] > target)                --j;            else                ++i;        }        return false;    }};
思路2:分治思想

取矩阵的中心点元素x和查找的元素y 进行比较,如图

(1)如果x<y,则y不可能在A中,可以删除;

(2)如果x>y,则y不可能在D中,可以删除;

时间复杂度不容易分析出来,大概在O(n^0.5)~O(n)之间

代码如下:

class Solution {public:    bool searchMatrix(vector<vector<int>>& matrix, int target) {if (matrix.empty())return false;int m = matrix.size(), n = matrix[0].size();return find(matrix, 0, 0, m - 1, n - 1, target);}bool find(vector<vector<int>> &a, int x1, int y1, int x2, int y2, int target) {if ((x1 > x2) || (y1 > y2))return false;int midx = (x1 + x2) >> 1;int midy = (y1 + y2) >> 1;if (a[midx][midy] == target)return true;return (target < a[midx][midy]) ?(find(a, x1, y1, midx - 1, y2, target) || find(a, midx, y1, x2, midy - 1, target)) :(find(a, x1, midy + 1, x2, y2, target) || find(a, midx + 1, y1, x2, midy, target));}};


1 0
原创粉丝点击