题目描述
有一个NxM的整数矩阵,矩阵的行和列都是从小到大有序的。请设计一个高效的查找算法,查找矩阵中元素x的位置。
给定一个int有序矩阵mat,同时给定矩阵的大小n和m以及需要查找的元素x,请返回一个二元数组,代表该元素的行号和列号(均从零开始)。保证元素互异。
测试样例:
[[1,2,3],[4,5,6]],2,3,6
返回:[1,2]
class Finder {
public:
vector<int> findElement(vector<vector<int> > mat, int n, int m, int x) {
// write code here
vector<int> res;
if(mat.size() == 0||mat.size() != n ||mat[0].size() != m)
return res;
int i=n-1;
int j=0;
while(i>=0 && j<m){
if(mat[i][j] == x){
res.push_back(i);
res.push_back(j);
break;
//或者 return res;
}
else if(mat[i][j] < x){
j++;
}
else{
i--;
}
}
return res;
}
};
注意满足条件后跳出循环!!