作者: 负雪明烛
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:

  1. Integers in each row are sorted from left to right.
  2. 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++)的更多相关文章

  1. [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 ...

  2. [LeetCode] 74 Search a 2D Matrix(二分查找)

    二分查找 1.二分查找的时间复杂度分析: 二分查找每次排除掉一半不合适的值,所以对于n个元素的情况来说: 一次二分剩下:n/2 两次:n/4 m次:n/(2^m) 最坏情况是排除到最后一个值之后得到结 ...

  3. leetcode 74. Search a 2D Matrix 、240. Search a 2D Matrix II

    74. Search a 2D Matrix 整个二维数组是有序排列的,可以把这个想象成一个有序的一维数组,然后用二分找中间值就好了. 这个时候需要将全部的长度转换为相应的坐标,/col获得x坐标,% ...

  4. 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 ...

  5. [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 ...

  6. 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 ...

  7. 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 ...

  8. 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 ...

  9. [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 ...

随机推荐

  1. Excel-电话号码隐藏某几个数为*,起到保护信息作用;

    9.电话号码隐藏某几个数为*,起到保护信息作用: 方法一: =SUBSTITUTE(AG2,MID(AG2,4,5),"*****") 解释函数: MID(目标字符串,裁剪起始位置 ...

  2. Hive-删除表(drop、truncate的区别)

    Hive删除操作主要分为几大类:删除数据(保留表).删除库表.删除分区.我将以下图为例清空iot_devicelocation中的数据,之后再删除表.库等. 解释: use xpu123;   #使用 ...

  3. nrf51822 RAM不足分析

    之前了解过STM32 的内存分配问题,对于蓝牙芯片51822的内存分配问题把项目中,遇到了.bss和.data部分超了的问题,这其实就是声明的变量和stask 及 heap的大小总和超出了单片机的RA ...

  4. C语言入坑指南-数组之谜

    前言 在C语言中,数组和指针似乎总是"暧昧不清",有时候很容易把它们混淆.本文就来理一理数组和指针之间到底有哪些异同. 数组回顾 在分析之前,我们不妨回顾一下数组的知识.数组是可以 ...

  5. 避免UE4项目VS中误改源码.h文件导致编译时间长

    最近几天两次触发VS中误改UE4源码头文件,导致需要编译大量源码的情况:再好的习惯也有不可靠的时候,还是需要可靠方案解决这个问题:官方提供了预编译版本(即从Launcher中下载的版本),但是对于程序 ...

  6. Hive相关知识点

    ---恢复内容开始--- 转载:Hive 性能优化 介绍 首先,我们来看看Hadoop的计算框架特性,在此特性下会衍生哪些问题? 数据量大不是问题,数据倾斜是个问题. jobs数比较多的作业运行效率相 ...

  7. css系列,选择器权重计算方式

    CSS选择器分基本选择器(元素选择器,类选择器,通配符选择器,ID选择器,关系选择器), 属性选择器,伪类选择器,伪元素选择器,以及一些特殊选择器,如has,not等. 在CSS中,权重决定了哪些CS ...

  8. Logback设置保留日志文件个数

    Logback日志文件占用存储空间太多,设置保留文件个数,清理之前的文件. 主要由如下三个参数配合使用 maxHistory ,可选节点,控制保留的归档文件的最大数量,超出数量就删除旧文件,,例如设置 ...

  9. Java 8实现BASE64编解码

    Java一直缺少BASE64编码 API,以至于通常在项目开发中会选用第三方的API实现.但是,Java 8实现了BASE64编解码API,它包含到java.util包.下面我会对Java 8的BAS ...

  10. "delete this" in C++

    Ideally delete operator should not be used for this pointer. However, if used, then following points ...