分治算法(二)240. Search a 2D Matrix II【middle】03-04
来源:互联网 发布:如何建立数据分析模型 编辑:程序博客网 时间:2024/05/17 06:13
1、题目
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.
[ [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
.
2、解题思路
题目里提到高效算法,我首先想到的是二分查找,一行一行地进行同样的二分查找(分治思想),但是有点偷懒了,直接用了c++库里的binary_search,本来以为答案会超出时间限制,但是AC了。。。
3、代码如下
class Solution {public: bool searchMatrix(vector<vector<int>>& matrix, int target) { if (matrix.size() == 0)return false; int i = 0; while (i < matrix.size() && !binary_search(matrix[i].begin(), matrix[i].end(), target))i++;if (i < matrix.size() - 1)return true;elsereturn binary_search(matrix[matrix.size() - 1].begin(), matrix[matrix.size() - 1].end(), target); }};
4、一些说明
首先,在本地编译时加入<algorithm>头函数
其次,要考虑到空矩阵的情形:
1.0 matrix整个是空的,也就是
if (matrix.size() == 0)return false;
2.0 matrix不空,但每一行都是空的
while (i < matrix.size() && !binary_search(matrix[i].begin(), matrix[i].end(), target))
注意,要先检查size,再进入二分搜索,不然很可能有运行时错误(利用到了短路?就是前一个为false,&&的第二个会被跳过)
0 0
- 分治算法(二)240. Search a 2D Matrix II【middle】03-04
- Middle-题目32: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
- tensorflow nan 原因总结
- GDB十分钟教程
- PAT_A 1027. Colors in Mars (20)
- POJ2236 Wireless Network(并查集)
- 交叉熵代价函数+方向导数+梯度(详细作用及公式推导)
- 分治算法(二)240. Search a 2D Matrix II【middle】03-04
- openJudge 全排列算法
- python类定义。
- 校门外的树
- 2017.03.04 C/C++小知识点
- Laravel+composer+git+terminal
- Android Studio 一直卡在Gradle:Build Running的解决办法
- 第一份博客编写
- MongoDB【第二篇】集群搭建