[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.

 

突然發現LeetCode很喜歡從LintCode上盜題,這是逼我去刷LintCode的節奏么?! 這道題讓我們在一個二維數組中快速的搜索的一個數字,這個二維數組各行各列都是按遞增順序排列的,是之前那道Search a 2D Matrix 搜索一個二維矩陣的延伸,那道題的不同在於每行的第一個數字比上一行的最后一個數字大,是一個整體蛇形遞增的數組。所以那道題可以將二維數組展開成一個一位數組用一次二查搜索。而這道題沒法那么做,這道題有它自己的特點。如果我們觀察題目中給的那個例子,我們可以發現有兩個位置的數字很有特點,左下角和右上角的數。左下角的18,往上所有的數變小,往右所有數增加,那么我們就可以和目標數相比較,如果目標數大,就往右搜,如果目標數小,就往上搜。這樣就可以判斷目標數是否存在。當然我們也可以把起始數放在右上角,往左和下搜,停止條件設置正確就行。代碼如下:

 

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

 

LeetCode All in One 題目講解匯總(持續更新中...)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM