且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

[LeetCode]240.Search a 2D Matrix II

更新时间:2022-08-12 18:35:48

题目

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.

思路

杨氏矩阵

代码

/*---------------------------------------
*   日期:2015-08-01
*   作者:SJF0115
*   题目: 240.Search a 2D Matrix II
*   网址:https://leetcode.com/problems/search-a-2d-matrix-ii/
*   结果:AC
*   来源:LeetCode
*   博客:
-----------------------------------------*/
#include <iostream>
#include <vector>
#include <stack>
using namespace std;

class Solution {
public:
    bool searchMatrix(vector<vector<int>>& matrix, int target) {
        if(matrix.empty()){
            return false;
        }//if
        int row = matrix.size();
        int col = matrix[0].size();
        int x = 0,y = col - 1;
        // 杨氏矩阵解法从右上角元素开始
        while(x < row && y >= 0){
            if(matrix[x][y] == target){
                return true;
            }//if
            else if(matrix[x][y] < target){
                ++x;
            }//else
            else{
                --y;
            }
        }//while
        return false;
    }
};

int main(){
    Solution s;
    int target = 20;
    vector<vector<int> > 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}
    };
    bool result = s.searchMatrix(matrix,target);
    // 输出
    cout<<result<<endl;
    return 0;
}