题解 | #矩阵元素查找#

矩阵元素查找

http://www.nowcoder.com/practice/3afe6fabdb2c46ed98f06cfd9a20f2ce

从右上角开始搜索,如果该值小于x,那么i++;如果该值大于x,那么j--。直至找到该值,或者数组越界为止。

class Solution {
public:
    vector<int> findElement(vector<vector<int> > mat, int n, int m, int x) {
        // write code here
        int i=0,j=m-1;
        while(i<n&&j>=0){
            if(mat[i][j]==x){
                return {i,j};
            }else if(mat[i][j]>x){
                j--;
            }else i++;
        }
        return {};
    }
};
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务