LeetCode#240 Search a 2D Matrix II
来源:互联网 发布:seo全套视频教程 编辑:程序博客网 时间:2024/05/21 22:47
[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 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
.
class Solution {public: bool searchMatrix(vector<vector<int>>& matrix, int target) { int size = matrix.size(); if (size == 0) return false; int x = 0, y = matrix[0].size()-1; while (y >= 0 && x < size) { if (matrix[x][y] == target) { return true; } else if (matrix[x][y] < target) { x++; } else { y--; } } return false; }};
这道题上我花了一些时间,也帮我更好的理解了分治法的思想。
原本我的思路是每一步比较对角线的中点和target的值,这样第一次比较就能减少1/4的区域,之后每次也会减少一部分,但是在结束比较了以后发现target可能出现的区域是两个矩形,随着矩阵规模的增大矩形也会变大。
即图中黄色区域。
这样子在两个矩形里搜索并没有什么改善。
于是我改变方法,从右上角的元素开始对比,若target大于此数字,则该元素所在列均不需要考虑,若target小于此数字,则该元素所在行均不需要考虑。这样在O(m+n)的时间里就可以完成一次对矩阵的搜索,效果不错。
阅读全文
0 0
- #leetcode#Search a 2D Matrix II
- [LeetCode] Search a 2D Matrix II
- leetcode: Search a 2D Matrix II
- leetcode - Search a 2D Matrix II
- [leetcode] Search a 2D Matrix II
- 【leetcode】Search a 2D Matrix II
- Leetcode: Search a 2D Matrix II
- LeetCode Search a 2D Matrix II
- [Leetcode]Search a 2D Matrix II
- [LeetCode]Search a 2D Matrix II
- LeetCode Search a 2D Matrix II
- [LeetCode]Search a 2D Matrix II
- LeetCode || Search a 2D Matrix II
- LeetCode----Search a 2D Matrix II
- Leetcode: Search a 2D Matrix II
- *LeetCode-Search a 2D Matrix II
- Search a 2D Matrix II -- leetcode
- leetcode | Search a 2D Matrix II
- Spring Boot应用的健康监控
- APUE第九章笔记
- tablayout_viewpager
- 前景提取、去除背景(selectROI+Grabcut)
- HTTP请求方法及幂等性探究
- LeetCode#240 Search a 2D Matrix II
- CentOS 7 如何设置默认启动方式为命令行模式
- Snapdragon NPE SDK配置及用例
- Keytool类
- 必须不含字符 [子级], 因为该类型的内容类型为“仅元素”
- 探讨scrapy当中的pipeline何时获取item。
- 1.python是如何进行类型转换
- Linux笔记之计划任务
- SpringBoot多数据源及MyBatis配置详解