第二章 排序 || 第18节 有序矩阵查找练习题

题目

现在有一个行和列都排好序的矩阵,请设计一个高效算法,快速查找矩阵中是否含有值x。

给定一个int矩阵mat,同时给定矩阵大小nxm及待查找的数x,请返回一个bool值,代表矩阵中是否存在x。所有矩阵中数字及x均为int范围内整数。保证n和m均小于等于1000。
测试样例:

[[1,2,3],[4,5,6],[7,8,9]],3,3,10

返回:false

解析

  • C++版
class Finder {
public:
    bool findX(vector<vector<int> > mat, int n, int m, int x) {
        // write code here
        int col=0;
        int row=n-1;
        while(col<m&&row>=0)
        {
            if(mat[row][col]==x)
                return true;
            else if(mat[row][col]>x)
            {
                row--;
            }
            else 
                col++;
        }
        return false;
    }
};
  • Python版
# -*- coding:utf-8 -*-

class Finder:
    def findX(self, mat, n, m, x):
        # write code here
        row=n-1
        col=0
        while row>=0 and col<m:
            if mat[row][col]==x:
                return True;
            elif mat[row][col]>x:
                row-=1
            else:
                col+=1
        return False
    原文作者:ranjiewen
    原文地址: https://www.cnblogs.com/ranjiewen/p/9281830.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞