[CareerCup] 11.6 Search a 2D Matrix 搜索一个二维矩阵

简介:

11.6 Given an M x N matrix in which each row and each column is sorted in ascending order, write a method to find an element.

LeetCode上的原题,请参见我之前的博客Search a 2D Matrix 搜索一个二维矩阵Search a 2D Matrix II 搜索一个二维矩阵之二

class Solution {
public:
    bool findElement(vector<vector<int> > &matrix, int elem) {
        if (matrix.empty() || matrix[0].empty()) return false;
        int row = 0, col = matrix[0].size() - 1;
        while (row < matrix.size() && col >= 0) {
            if (matrix[row][col] == elem) return true;
            else if (matrix[row][col] < elem) ++row;
            else --col;
        }
        return false;
    }
};

 本文转自博客园Grandyang的博客,原文链接:搜索一个二维矩阵[CareerCup] 11.6 Search a 2D Matrix ,如需转载请自行联系原博主。

目录
打赏
0
0
0
0
5351
分享
相关文章
力扣240 搜索二维矩阵II
力扣240 搜索二维矩阵II
74_搜索二维矩阵
74_搜索二维矩阵
LeetCode第74题搜索二维矩阵
文章讲解了LeetCode第74题"搜索二维矩阵"的解决方案,利用二分搜索法将问题简化,并通过数学转换找到二维矩阵中的对应元素,展示了将二维问题转化为一维问题的解题技巧。
LeetCode第74题搜索二维矩阵
|
10月前
|
NumPy 分割与搜索数组详解
NumPy 的 `np.array_split()` 函数用于分割数组。基本语法是 `np.array_split(array, indices_or_sections, axis=None)`,它接受一个 NumPy 数组和分割参数,按指定轴进行分割。示例:将 `[1, 2, 3, 4, 5, 6]` 分割成 3 个子数组,结果是 `[[1, 2], [3, 4], [5, 6]]`。注意,超出数组范围的分割位置会导致异常,且元素数量可能根据需要调整。`np.array_split()` 返回子数组的列表。可以按列分割、使用掩码或不均匀分割。练习:将 `arr = [1, 2, 3, 4,
105 0
【二分查找】【z型搜索】LeetCode240:搜索二维矩阵
【二分查找】【z型搜索】LeetCode240:搜索二维矩阵
|
10月前
|
【Leetcode 74】搜索二维矩阵 —— 二分查找|矩阵
给你一个满足下述两条属性的`m x n`整数矩阵:每行中的整数从左到右按非严格递增顺序排列。每行的第一个整数大于前一行的最后一个整数
|
10月前
|
leetcode-240:搜索二维矩阵 II
leetcode-240:搜索二维矩阵 II
53 0
|
10月前
|
leetcode-74:搜索二维矩阵
leetcode-74:搜索二维矩阵
51 0
|
10月前
|
二维矩阵搜索问题——小米面试题
二维矩阵搜索问题——小米面试题
49 0
AI助理

你好,我是AI助理

可以解答问题、推荐解决方案等