欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

布洛克 NC86 矩阵元素查找 [中型分割、细分 C++/Java/Go/PHP] - C++ 参考答案

最编程 2024-04-29 07:01:04
...
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param mat int整型vector<vector<>> 
     * @param n int整型 
     * @param m int整型 
     * @param x int整型 
     * @return int整型vector
     */
    vector<int> findElement(vector<vector<int> >& mat, int n, int m, int x) {
        /*
           选择左下角为起点,以下展示了「减治」的过程。
           搜索的规律是:

           如果当前数比目标元素小,当前列就不可能存在目标值,「指针」就向右移一格(纵坐标加 1);
           如果当前数比目标元素大,当前行就不可能存在目标值,「指针」就向上移一格(横坐标减 1)。
           在编码的过程中要注意数组下标越界的问题。
            */
        // 起点:左下角
        int currow = n-1;
        int curcol = 0;

        // 不越界的条件是:行大于等于 0,列小于等于 cols - 1
        vector<int> ans = {-1,-1};
        while (currow >=0 && curcol<m){
            if(mat[currow][curcol] >x ){
                currow-=1;
            }else if(mat[currow][curcol] <x){
                curcol+=1;
            }else{
                ans[0] =currow;
                ans[1] =curcol;
                break;
            }
        }
        return ans;
    }
};