题解 | #矩阵元素查找#
矩阵元素查找
http://www.nowcoder.com/practice/3afe6fabdb2c46ed98f06cfd9a20f2ce
- 从右上角到左下角(包括)依次进行二分查找。
class Solution {
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){
res.push_back(row);
res.push_back(col);
break;
}else if(mat[row][col]<x){
row++;//证明从下一行开始找
}else{
col--;//证明在该行的左边
}
}
return res;
}
}; 算法解析 文章被收录于专栏
这里主要是算法岗的自我思路总结
查看7道真题和解析