牛客题霸 [矩阵元素查找] C++题解/答案
题目描述
已知int一个有序矩阵mat,同时给定矩阵的大小n和m以及需要查找的元素x,且矩阵的行和列都是从小到大有序的。设计查找算法返回所查找元素的二元数组,代表该元素的行号和列号(均从零开始)。保证元素互异。
题解:
因为行和列都是有序的,所以两个变量一个表示行一个表示列
通过比较,先找到对应的列,再找到对应的行
代码:
class Finder {
public:vector<int> findElement(vector<vector<int> > mat, int n, int m, int x) {// write code herevector<int> res;if(n==0||m==0)return res;int i=0,j=m-1;while(i<n&&j>=0){if(mat[i][j]>x)j--;else if(mat[i][j]<x)++i;else{res.push_back(i);res.push_back(j);break;}}return res;}
};