作者: 负雪明烛
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 in ascending from left to right.
  2. Integers in each column are sorted in ascending from top to bottom.

Example:

Consider the following matrix:

[
[1, 4, 7, 11, 15],
[2, 5, 8, 12, 19],
[3, 6, 9, 16, 22],
[10, 13, 14, 17, 24],
[18, 21, 23, 26, 30]
]

Given target = 5, return true.

Given target = 20, return false.

题目大意

怪我理解能力太差?谁告诉我和74. Search a 2D Matrix的区别?

给出了有规则的二维矩阵,规则是从左向右依次递增,从上向下依次递增。进行查找。

解题方法

74. Search a 2D Matrix完全一样的代码就A了。。我都蒙的。

下面是解释。

这个题在剑指offer的38-40页有详细解释。方法是从右上角向左下角进行遍历,根据比较的大小决定向下还是向左查找。

剑指offer的解释是我们从矩阵的左下角或者右上角开始遍历,这样知道了比较的结果是大还是小,就知道了对应的前进方向。

Python代码:

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();
int i = M - 1, j = 0;
while (i >= 0 && j < N) {
if (matrix[i][j] == target) {
return true;
} else if (matrix[i][j] < target) {
++j;
} else {
--i;
}
}
return false;
}
};

方法二:

暴力解法遍历,这也能过。。我实在看不懂leetcode了。。

class Solution(object):
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
return any(target in row for row in matrix)

日期

2018 年 3 月 6 日
2019 年 1 月 7 日 —— 新的一周开始啦啦啊

最新文章

  1. ADO.NET存取数据库数据
  2. 自己写了一个无缝滚动的插件(jQuery)
  3. Linux GCC常用命令
  4. UI事件监听的击穿
  5. 利用maven的resources、filter和profile实现不同环境使用不同配置文件
  6. 生成元(Digit Generator,ACM/ICPC Seoul 2005,UVa 1583)
  7. BZOJ 1085: [SCOI2005]骑士精神(A*算法)
  8. Intellij idea 离线安装activiti工作流插件
  9. MongoDB复合索引详解
  10. Spring MVC 5 + Thymeleaf 基于Java配置和注解配置
  11. 将本地时间转换成 UTC 时间,0时区时间
  12. (原)tensorflow使用eager在mnist上训练的简单例子
  13. ***使用Fiddler抓取Android安卓手机的APP请求
  14. 强制SVN上传代码时添加日志
  15. ogg 12.3 for sqlserver 2016 CDC模式配置
  16. navicat连接虚拟机中mysql&quot;Access denied for user&#39;root&#39;@&#39;IP地址&#39;&quot;问题
  17. Kruskal重构树学习笔记+BZOJ3732 Network
  18. FastReport 变量列表使用
  19. Spring分配置文件开发
  20. Javascript设计模式理论与实战:组合模式

热门文章

  1. MybatisPlus的CRUD及拓展
  2. WebRTC本地分享屏幕,录制屏幕
  3. account, accomplish, accumulate
  4. Java、Scala类型检查和类型转换
  5. Hbase与Phoenix整合
  6. ssh : connect to host XXX.XXX.XXX.XXX port : 22 connect refused
  7. 一份不错的Java就业指导
  8. t01_docker安装TiDB
  9. Spring Boot 和 Spring Cloud Feign调用服务及传递参数踩坑记录
  10. 计算机网络 Raw_Socket编程 Ping C语言