LeetCode——Search a 2D Matrix

Question

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 from left to right.
The first integer of each row is greater than the last integer of the previous row.
For example,

Consider the following matrix:

[
  [1,   3,  5,  7],
  [10, 11, 16, 20],
  [23, 30, 34, 50]
]

Given target = 3, return true.

Solution

因为第一行的最后一个数字是那一行最大的,那一列最小的,如果它比目标值大,那肯定不在那一列,那么就可以去掉一列;如果它比目标值小,那么肯定不在那一行,可以去掉那一行。

Code

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

注意边界条件的写法

posted @ 2017-09-17 11:45  清水汪汪  阅读(238)  评论(0编辑  收藏  举报