LeetCode—74. Search a 2D Matrix

Type:medium

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.


在一个矩阵中找某个数。


bool searchMatrix(vector>& matrix, int target) {

        if(matrix.empty() || matrix[0].empty()) return false;

        int m = matrix.size();

        int n = matrix[0].size();

        int row = 0;

        if(matrix[0][0] > target) return false;

        for(int i=0; i

            if(matrix[i][0] == target) return true;

            if(matrix[i][0] > target){

                row = i - 1;

                break;

            }else row = i;

        }

        for(int i=0; i

            if(matrix[row][i] == target) return true;

        }

        return false;

    }

你可能感兴趣的:(LeetCode—74. Search a 2D Matrix)