# 74. Search a 2D Matrix

## 1.問題

* 判斷是否可以在矩陣中找到target, 矩陣的特性如下:
  * 每一row的排序為由左到右升冪
  * 每一col的順序為由上到下升冪

![](https://901207480-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LGKoChvN9am4__HCIRK%2F-LNd8lhKJEn4x3H-VjAU%2F-LNd9t_sM0-FX4a4jXwB%2F%E8%9E%A2%E5%B9%95%E5%BF%AB%E7%85%A7%202018-09-30%20%E4%B8%8B%E5%8D%882.29.43.png?alt=media\&token=3fc4cb07-f5df-4fc4-97d6-3e6fc8433ccf)

## 2.想法&#x20;

* 提問:
* function header, parameter
* test input
* 說明想法&#x20;
  * 由於此陣列的排列順序為左到右, 上到下ascending排序, 因此可以先從右上角開始, 與target比較, 如果該點大於target, 則左移該點; 如果該點小於target, 則下移該點
* 測試計算複雜度

## 3.程式碼

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