在行列都排好的矩阵中找数

  • 在行列都排好的矩阵中找数

题目来源

  • 题目思路

  • C++代码实现

#include <vector>
#include <iostream>
using namespace std;

class Solution
{
public:
    bool IsExist(vector<vector<int>>& matrix, int k)
    {
        bool existence = false;

        int row = matrix.size();
        int col = matrix[0].size();

        int a = 0;
        int b = col - 1;

        while (a < row && b >= 0)
        {
            if (matrix[a][b] > k)
            {
                b--;
            }
            else if (matrix[a][b] < k)
            {
                a++;
            }
            else if (matrix[a][b] == k)
            {
                existence = true;
                break;
            }
        }

        return existence;
    }
};

int main()
{
    int n = 0;
    int m = 0;
    int k = 0;
    cin >> n;
    cin >> m;
    cin >> k;

    vector<vector<int>> matrix(n, vector<int>(m));
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < m; j++)
        {
            cin >> matrix[i][j];
        }
    }
    Solution s;
    if (s.IsExist(matrix, k))
    {
        cout << "Yes";
    }
    else
    {
        cout << "No";
    }
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/Manual-Linux/p/12070317.html
今日推荐