[leetcode_240]Search a 2D Matrix II

因为矩阵的特殊性,所有从左上角顶点开始搜索即可。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
public:
    bool searchMatrix(vector<vector<int>>& matrix, int target) {
        int row = matrix.size() - 1;
        int cols = matrix[0].size() - 1;
        int x = 0;
        int y = cols;
        while (x <= row && y >= 0)
        {
            if (target == matrix[x][y])
            {
                return true;
            }
            else if (target > matrix[x][y])
            {
                x++;
            }
            else
            {
                y--;
            }
        }
        return false;
    }
};
Licensed under CC BY-NC-SA 4.0