【LeetCode】74. Search a 2D Matrix 解题报告(Python & C++)
作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/
题目地址:https://leetcode.com/problems/search-a-2d-matrix/description/
题目描述
Write an efficient algorithm that searches for a value in an m x n
matrix. This matrix has the following properties:
- Integers in each row are sorted from left to right.
- The first integer of each row is greater than the last integer of the previous row.
Example 1:
Input:
matrix = [
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
target = 3
Output: true
Example 2:
Input:
matrix = [
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
target = 13
Output: false
题目大意
给出了有规则的二维矩阵,规则是从左向右依次递增,每行的起始元素比上一行的最后一个元素大。进行查找。
解题方法
左下或者右上开始查找
这个题目是240. Search a 2D Matrix II的一个特例,所以可以直接使用240题的代码就能通过。方法是从矩阵的左下角或者右上角开始遍历。
这个题在剑指offer的38-40页有详细解释。方法是从右上角向左下角进行遍历,根据比较的大小决定向下还是向左查找。
代码:
class Solution(object):
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
if not matrix or not matrix[0]:
return False
rows = len(matrix)
cols = len(matrix[0])
row, col = 0, cols - 1
while True:
if row < rows and col >= 0:
if matrix[row][col] == target:
return True
elif matrix[row][col] < target:
row += 1
else:
col -= 1
else:
return False
顺序查找
我想这个题目要考察的并不是上面这个方法,而是一个更简单的方法,即顺序查找。我们从第一行开始向下面进行查找,如果这行的末尾元素比当前要查找的元素大,那么说明要查找的元素就在这行里。在这行里查找元素很简单啦,就不多少了。
C++代码如下:
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
if (matrix.size() == 0 || matrix[0].size() == 0) return false;
const int M = matrix.size(), N = matrix[0].size();
for (int i = 0; i < M; ++i) {
if (target > matrix[i][N - 1])
continue;
auto it = find(matrix[i].begin(), matrix[i].end(), target);
return it != matrix[i].end();
}
return false;
}
};
受到上面的解法启发,我们可以直接遍历每一个位置进行查找啊!怎么做?矩阵的顺序遍历只需要一个变量i表示位置即可,matrix[i/N][i%N]即为当前遍历到的元素。
这个做法的C++代码如下:
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
if (matrix.size() == 0 || matrix[0].size() == 0) return false;
const int M = matrix.size(), N = matrix[0].size();
int i = 0;
while (i < M * N) {
if (matrix[i / N][i % N] == target)
return true;
++i;
}
return false;
}
};
库函数
使用库函数也可以哦,不过库函数都是针对一维数组的查找,所以我们需要把给出的数组变成一维的。在numpy中有reshape函数,幸运的是,leetcode支持Numpy.
python代码如下:
import numpy as np
class Solution(object):
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
matrix = np.reshape(matrix, [1, -1])
return target in matrix
日期
2018 年 3 月 6 日
2019 年 1 月 7 日 —— 新的一周开始啦啦啊
【LeetCode】74. Search a 2D Matrix 解题报告(Python & C++)的更多相关文章
- [LeetCode] 74. Search a 2D Matrix 解题思路
Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the follo ...
- [LeetCode] 74 Search a 2D Matrix(二分查找)
二分查找 1.二分查找的时间复杂度分析: 二分查找每次排除掉一半不合适的值,所以对于n个元素的情况来说: 一次二分剩下:n/2 两次:n/4 m次:n/(2^m) 最坏情况是排除到最后一个值之后得到结 ...
- leetcode 74. Search a 2D Matrix 、240. Search a 2D Matrix II
74. Search a 2D Matrix 整个二维数组是有序排列的,可以把这个想象成一个有序的一维数组,然后用二分找中间值就好了. 这个时候需要将全部的长度转换为相应的坐标,/col获得x坐标,% ...
- LeetCode: Search a 2D Matrix 解题报告
Search a 2D Matrix Write an efficient algorithm that searches for a value in an m x n matrix. This m ...
- [LeetCode] 74. Search a 2D Matrix 搜索一个二维矩阵
Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the follo ...
- leetCode 74.Search a 2D Matrix(搜索二维矩阵) 解题思路和方法
Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the follo ...
- LeetCode 74. Search a 2D Matrix(搜索二维矩阵)
Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the follo ...
- leetcode 74. Search a 2D Matrix
Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the follo ...
- [LeetCode] 240. Search a 2D Matrix II 搜索一个二维矩阵 II
Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the follo ...
随机推荐
- 『学了就忘』Linux文件系统管理 — 62、手动分配swap分区
目录 1.查看swap分区情况 2.手动修改swap分区 3.格式化swap分区 4.使用swap分区 5.配置swap分区开机之后自动挂载 1.查看swap分区情况 swap分区就相当于是内存的一个 ...
- [源码解析] PyTorch分布式优化器(1)----基石篇
[源码解析] PyTorch分布式优化器(1)----基石篇 目录 [源码解析] PyTorch分布式优化器(1)----基石篇 0x00 摘要 0x01 从问题出发 1.1 示例 1.2 问题点 0 ...
- LeetCode替换空格
LeetCode 替换空格 题目描述 请实现一个函数,把字符串 s 中的每个空格替换成"%20". 实例 1: 输入:s = "We are happy." 输 ...
- 论 Erda 的安全之道
作者|陈建锋 来源|尔达 Erda 公众号 软件研发是一个复杂的工程,不仅需要进行软件的设计.开发.测试.运维,还涉及到大量的人力.物力管理.今天讨论的主角 - "安全",在软 ...
- day14 linux三剑客之sed命令
day14 linux三剑客之sed命令 sed命令 Sed 主要用来自动编辑一个或多个文件.简化对文件的反复操作.编写转换程序等. sed(流式编辑器) : sed主要用来修改文件. 1.sed命令 ...
- Hive(四)【DML 数据导入导出】
目录 一.数据导入 1.1 [load]--向数据中装载数据 案例 1.2 [insert]--查询语句向表中插入数据 案例 1.3 [as select]--查询语句中创建表且加载数据 案例 1.4 ...
- 银联acp手机支付总结
总结: 1.手机调用后台服务端接口,获取银联返回的流水号tn 银联支付是请求后台,后台向银联下单,返回交易流水号,然后返回给用户,用户通过这个交易流水号,向银联发送请求,获取订单信息,然后再填写银行卡 ...
- Python 基于python实现的http+json协议接口自动化测试框架源码(实用改进版)
目录 1. 写在前面 2. 开发环境 3. 大致流程 4. 框架简介 5. 运行结果展示 6. 文件与配置 7. 测试接口实例 n ...
- 2.8 rust 枚举与模式匹配
Enums and Pattern Matching 摘要 枚举定义 enum IpAddrKind { V4, V6, } 枚举方法 fn main() { enum Message { Quit, ...
- Jenkins代码检查
目录 一.静态代码分析 二.规范检查 PMD进行检查 分析器区别 三.持续代码质量检测 Maven与SonarQube集成 Jenkins与SonarQube集成 代码扫描 SonarQube集成p3 ...