题解 | #矩阵元素查找#
矩阵元素查找
https://www.nowcoder.com/practice/3afe6fabdb2c46ed98f06cfd9a20f2ce
class Solution {
public:
vector<int> findElement(vector<vector<int> > mat, int n, int m, int x) {
for (int i = n - 1, j = 0; i >= 0 && j < m; ) {
if (mat[i][j] == x) {
return {i, j};
} else if (mat[i][j] > x) {
--i;
} else {
++j;
}
}
return {-1, -1};
}
};
思路:从左下角(或右下角)开始查找。
比较当前元素matij与目标x:
* 如果相等则直接返回。
* 如果matij较大,则matij所处行右边的元素也一定大于x,所以减少matij的行号。
* 否则,matij所处列上面的元素也一定小于x,所以增大matij的列号。
查看19道真题和解析