牛客题霸 [矩阵查找] C++题解/答案

牛客题霸 [矩阵查找] C++题解/答案

题目描述

请写出一个高效的在m*n矩阵中判断目标值是否存在的算法,矩阵具有如下特征:
每一行的数字都从左到右排序
每一行的第一个数字都比上一行最后一个数字大
例如:
对于下面的矩阵:
[
[1, 3, 5, 9],
[10, 11, 12, 30],
[230, 300, 350, 500]
]
要搜索的目标值为3,返回true;

题解:

矩阵是排好序的,直接从左上开始根据大小找即可

代码:

class Solution {
public:
    /**
     * 
     * @param matrix int整型vector<vector<>> 
     * @param target int整型 
     * @return bool布尔型
     */
    bool searchMatrix(vector<vector<int> >& matrix, int target) {
        // write code here
        int len=matrix[0].size()-1;
        int x=0;
        while(x<matrix.size()&&len>=0)
        {
            if(target==matrix[x][len])
            {
                return 1;
            }
            else if(target<matrix[x][len])len--;
            else if(target>matrix[x][len])x++;
        }
        return 0;
    }
};
posted @ 2020-11-19 22:06  回归梦想  阅读(105)  评论(0编辑  收藏  举报