題目描述
有一個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;
int row = 0;
int col = m - 1;
while(row < n && col >= 0)
{
if(mat[row][col] > x)
{
--col;
}
else if(mat[row][col] < x)
{
++row;
}
else
{
res.push_back(row);
res.push_back(col);
return res;
}
}
return res;
}
};