LeetCode Search a 2D Matrix

来源:互联网 发布:高仿充q币软件 编辑:程序博客网 时间:2024/06/07 07:21

题目链接:https://oj.leetcode.com/problems/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.


由于这个矩阵是有序的,我们可以从右上角开始进行比较,若比右上角大,则肯定在下一行,否则就在本行中,时间复杂度O(m+n)


当然也可以用二分来做,同样从最右边那一列开始看,先二分出是在哪一行,然后再二分出是在哪一列时间复杂度 O(logn+logm)


下面给出O(m+n)的代码


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


0 0
原创粉丝点击