[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;
    }
};


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