240. Search a 2D Matrix II
来源:互联网 发布:西部世界好看吗 知乎 编辑:程序博客网 时间:2024/06/05 06:57
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 in ascending from left to right.
- Integers in each column are sorted in ascending from top to bottom.
For 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
.
java
class Solution { public boolean searchMatrix(int[][] matrix, int target) { if (matrix == null || matrix.length == 0) { return false; } if (matrix[0] == null || matrix[0].length == 0) { return false; } int row = 0; int column = matrix[0].length - 1; while (row < matrix.length && column >= 0) { if (matrix[row][column] == target) { return true; } else if (matrix[row][column] > target) { column--; } else { row++; } } return false; }}
python
class Solution(object): def searchMatrix(self, matrix, target): """ :type matrix: List[List[int]] :type target: int :rtype: bool """ if matrix is None or len(matrix) == 0: return False if matrix[0] is None or len(matrix[0]) == 0: return False row, column = 0, len(matrix[0]) - 1 while row < len(matrix) and column >= 0: if matrix[row][column] == target: return True elif matrix[row][column] > target: column -= 1 else: row += 1 return False
阅读全文
0 0
- 240. Search a 2D Matrix II
- 240. Search a 2D Matrix II
- 240. Search a 2D Matrix II
- 240. Search a 2D Matrix II
- 240. Search a 2D Matrix II
- 240. Search a 2D Matrix II
- 240. Search a 2D Matrix II
- 240. Search a 2D Matrix II
- 240. Search a 2D Matrix II
- 240. Search a 2D Matrix II
- 240. Search a 2D Matrix II
- 240. Search a 2D Matrix II
- 240. Search a 2D Matrix II
- 240. Search a 2D Matrix II
- 240. Search a 2D Matrix II
- 240. Search a 2D Matrix II
- 240. Search a 2D Matrix II
- 240.Search a 2D Matrix II
- Linux sh执行sql语句
- C语言实现Openssl+CURL+nginx 单向认证
- 欢迎使用CSDN-markdown编辑器
- 线性代数--线性无关4
- c++数值转字符串
- 240. Search a 2D Matrix II
- 看着头疼也难懂的JS程序
- 05-树8 File Transfer(25 point(s))
- java.lang.NoClassDefFoundError: Failed resolution of: Landroid/support4/animation/AnimatorCompatHelp
- socket中的发送与接收函数
- Linux上VNC 启动和关闭 常见问题
- 利用wordcloud生成云图
- python学习-Day10-文件操作
- shell脚本自动检查hdfs集群各数据节点的磁盘空间使用率[附代码]