LeetCode 240. Search a 2D Matrix II

    xiaoxiao2021-03-25  63

    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 in ascending from left to right.Integers in each column are sorted in ascending from top to bottom.

    For example,

    Consider the following matrix:

    [ [1, 4, 7, 11, 15], [2, 5, 8, 12, 19], [3, 6, 9, 16, 22], [10, 13, 14, 17, 24], [18, 21, 23, 26, 30] ]

    Given target = 5, return true.

    Given target = 20, return false.

    m x n矩阵中,每一行和每一列都是从小到大排列,要求判断一个值是否属于该矩阵。

    解决思路:从右上角或从左下角的元素开始搜索。以右上角为例:

    如果元素的值等于target,则返回true;

    如果元素的值小于target,则应该搜索左边的元素;

    如果元素的值大于target,则应当搜索下面的元素;

    当左边或者下面没有元素的时候,结束循环,返回false。

    代码实现如下:

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

    转载请注明原文地址: https://ju.6miu.com/read-37193.html

    最新回复(0)