[LeetCode]--Search a 2D Matrix II

题目

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 in ascending from left to right.
  • Integers in each column are sorted in ascending from top to bottom.

For example,

Consider the following matrix:

[
  [1,   4,  7, 11, 15],
  [2,   5,  8, 12, 19],
  [3,   6,  9, 16, 22],
  [10, 13, 14, 17, 24],
  [18, 21, 23, 26, 30]
]

Given target = 5, return true.

Given target = 20, return false.

分析

       这是一道递归与分治的类型题,搜索矩阵中的元素,我们首先想到的是遍历整个矩阵,也即一个二维数组,然后逐个对比,若搜索到目标元素,则返回true;若无法找到,则返回false。然而这样的方法是非常不经济的,其时间复杂度为O(m*n),其中m、n分别为矩阵的行数和列数。
       而根据题意,矩阵的每一行都按照由小到大的顺序排列,每一列也以升序排列。这样,我们可以两个维度同时比较,也即由整个矩阵的右上角开始,若该位置元素大于目标元素时,则将列数减1,即左移一个位置;若该位置元素小于目标元素时,则将行数加1,即下移一个位置进行比较;若等于目标元素,则返回true;否则返回false。
       此种算法的时间复杂度为O(m+n),其中m、n分别为矩阵的行数和列数。

解答

class Solution {
public:
    bool searchMatrix(vector<vector<int>>& matrix, int target) {
        int row=matrix.size();
        if(row==0)
            return false;
        int col=matrix[0].size();
        
        int i=0;
        int j=col-1;
        while(i<row && j>=0){
            if(matrix[i][j]==target){
                return true;
            }
            else if(matrix[i][j]>target){
                j=j-1;
            }
            else{
                i=i+1;
            }
        }
        return false;
    }
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章