栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

[LeetCode]240. Search a 2D Matrix II 搜索二维矩阵 II

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

[LeetCode]240. Search a 2D Matrix II 搜索二维矩阵 II

发艾恩凝

个人博客  https://aeneag.xyz/ 

每日一题,菜鸡要学飞

目录

题目链接

题解

错误


题目链接

https://leetcode-cn.com/problems/search-a-2d-matrix-ii/

题解

此题用暴力法就可以很简单的解决,不就是个二维数组,直接挨个搜索比对,也可以用二分查找,另外一种方法就是从左下角或者右上角搜索,拿右上角举例,左边的都比这个小,下面的都比这个大,这就可以排除了

class Solution {
public:
    bool searchMatrix(vector>& matrix, int target) {
        int col = matrix[0].size(),row = matrix.size();
        int i = 0 ,j = col - 1 ;
        if(!row&&!col)return false;
        while(i < row && j >= 0){
            if(matrix[i][j] == target)return true;
            else if(matrix[i][j] < target)++i;
            else if(matrix[i][j] > target)--j;
        }
        return false;
    }
};

错误

Line 1033: Char 9: runtime error: reference binding to null pointer of type ‘int‘ (stl_vector.h)

这个错误其实就是数组越界,

原先是这样写的

if(matrix[i][j] == target)return true;
if(matrix[i][j] < target)++i;
if(matrix[i][j] > target)--j;
if(matrix[i][j] == target)return true;
else if(matrix[i][j] < target)++i;
else if(matrix[i][j] > target)--j;

改成上面的就运行通过了,有时不明白LeetCode运行机制,越界在哪里

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/303231.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号