leetcode(240). Search a 2D Matrix II
来源:互联网 发布:怎么在淘宝进货 编辑:程序博客网 时间:2024/06/04 00:29
problem
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.
solution
这个问题可以看做是二分查找的拓展,都是从中间找到一个点,与之相比,然后排除一部分不可能的点。
下面是一个递归的解法,时间复杂度为
问题:有没有更好的解法?
如果每次比较的是最中间的元素的话,每次可以至少删除1/4个元素,也就是
class Solution(object): def searchMatrix(self, matrix, target): """ :type matrix: List[List[int]] :type target: int :rtype: bool """ m = len(matrix) if m == 0: return False n = len(matrix[0]) def find(matrix, ms, me, ns, ne, t): if ms > me or ns >ne: return False # print(matrix[ms][ne]) if t == matrix[ms][ne]: return True elif t > matrix[ms][ne]: return find(matrix, ms+1, me, ns, ne, t) else: return find(matrix, ms, me, ns, ne-1, t) return find(matrix, 0, m-1, 0, n-1, target)
仿照这个思路可以写成循环的形式,性能会提升一些。
阅读全文
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
- Django是怎么处理请求的
- 数据类型注意要点2017-9-6
- [OpenWRT交叉编译]运行ndppd提示can't load library 'libstdc++.so.6的解决方案
- meta 属性整理
- python设计模式之建造者
- leetcode(240). Search a 2D Matrix II
- java开发多国语言互译
- js函数节流
- 51Nod1062 序列中最大的数
- BZOJ 1010 [HNOI2008]玩具装箱
- Laravel 学习路线【2】路由
- 拥抱梵谷-蒋勋有声
- 理解一个应用结构
- 将字符串数据按照指定的编码写入到文本文件中