【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 ...
随机推荐
- 12 — springboot集成JPA — 更新完毕
1.什么是jpa? 一堆不想整在这博客里面的理论知识.这些理论玩意儿就应该自行领悟到自己脑海里 1).JPA & Spring Data JPA 1.1).JPA JPA是Java Persi ...
- addict, address, adequate.四级
addict addiction – a biopsychosocial [生物社会心理学的 bio-psycho-social] disorder characterized by persiste ...
- HDFS【概述、数据流】
目录 概述 定义 优缺点 HDFS组成架构 HDFS文件块大小 HDFS数据流 写数据 读数据 网络拓扑-节点距离计算 机架感知(写数据的副本存储节点选择) 概述 定义 HDFS是一个分布式文件管理系 ...
- What all is inherited from parent class in C++?
派生类可以从基类中继承: (1)基类中定义的每个数据成员(尽管这些数据成员在派生类中不一定可以被访问): (2)基类中的每个普通成员函数(尽管这些成员函数在派生类中不一定可以被访问): (3)The ...
- oracle(数据备份)
1 --oracle数据备份(三种方法) 2 --1.逻辑备份与恢复:用Oracle提供的工具,导入/导出(exp,imp),数据 3 --泵导入/导出(impdp,expdp),装入器(SQL*Lo ...
- Appium获取toast消息(二)
刚接触appium进行移动端设备的UI自动化,在遇到toast消息的时候很是苦恼了一阵,最后通过强大的搜索引擎找到了个相对解决方法,废话不多说,直接贴代码↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓ ...
- jQuery节点更新
一.插入子节点 var $newNode1 = $("<p>我是p标签</p>"); 加入之后,原来的会删除. 二.插入兄弟节点 三.替换节点 1.HTML ...
- 记ByteCTF中的Node题
记ByteCTF中的Node题 我总觉得字节是跟Node过不去了,初赛和决赛都整了个Node题目,当然PHP.Java都是必不可少的,只是我觉得Node类型的比较少见,所以感觉挺新鲜的. Nothin ...
- Log4j漏洞源码分析
Log4j漏洞源码分析 这几天Log4j的问题消息满天飞,今天我们就一起来看看从源码角度看看这个漏洞是如何产生的. 大家都知道这次问题主要是由于Log4j中提供的jndi的功能. 具体涉及到的入口类是 ...
- STL模板前言(1)
STL提供以下数据结构方便使用: 顺序容器: vector(动态数组):从后面直接插入删除元素,直接访问任何元素. deque(双端队列):从前面和后面快速插入删除,直接访问任何元素. list(双链 ...