[leetcode_240]Search a 2D Matrix II

Due to the special properties of the matrix, we can simply start searching from the top-left corner.

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