Leetcode NO.74 Search a 2D Matrix
来源:互联网 发布:批量剪裁图片软件 编辑:程序博客网 时间:2024/05/04 07: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 from left to right.
- The first integer of each row is greater than the last integer of the previous row.
For example,
Consider the following matrix:
[ [1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50]]
Given target = 3
, return true
.
本题最开始秒想出一种O(mn)的算法,就是把matrix完全展开,就是一个sorted array,然后用binary search,提交之后一次通过了,不过一看这是medium题,感觉怪怪的。。。于是又想了一会儿,想出一种O(log(m)+log(n))的方法。思路也是比较简单,但是处理边界条件花了我一点时间。
直接上代码:
class Solution {public: bool searchMatrix(vector<vector<int> > &matrix, int target) { int m = matrix.size(); int n = matrix[0].size(); int row = -1; int low = 0; int high = m - 1; int mid = 0; while (low <= high) { mid = (high + low) / 2; if (matrix[mid][0] == target) return true; else if (matrix[mid][0] > target) high = mid - 1; else { if (matrix[mid][n-1] >= target) { row = mid; break; } else low = mid + 1; } } if (row == -1) return false; low = 1; high = n - 1; while (low <= high) { mid = (low + high) / 2; if (matrix[row][mid] == target) return true; else if (matrix[row][mid] > target) high = mid - 1; else low = mid + 1; } return false; }};
算法解释:
本题用了两次binary search:
1,第一次复杂一点,需要处理边界条件,如果matrix[mid][0]比target小的话,不能单纯的直接low = mid + 1,因为即使这样target也可能在mid这一行,所以需要检查matrix[mid][n-1]是否大于target,如果大于target,则返回这一行为row,否则按binary search的通常步骤处理
2,如果第一次binary search中没有找到target > matrix[mid][0], target < matrix[mid][n-1]的那行,即该target < matrix[0][0]或者 > matrix[m-1][n-1],无论是哪种可能,在循环中都不会对row赋值,这种情况就直接判定为false
3,第二次在确定的行内搜索就是普通的binary search
- Leetcode NO.74 Search a 2D Matrix
- Leetcode No.74 Search a 2D Matrix
- LeetCode--No.74--Search a 2D Matrix
- LeetCode No.240 Search a 2D Matrix II
- LeetCode No.240 Search a 2D Matrix II
- Leetcode 74 Search a 2D Matrix
- LeetCode 74: Search A 2D Matrix
- LeetCode 74 Search a 2D Matrix
- [leetcode 74] Search a 2D Matrix
- [LeetCode 74]Search a 2D Matrix
- leetcode || 74、Search a 2D Matrix
- leetcode-74 Search a 2D Matrix
- Leetcode[74]-Search a 2D Matrix
- 【Leetcode】Search a 2D Matrix #74
- LeetCode(74) Search a 2D Matrix
- Leetcode #74 Search a 2D Matrix
- Leetcode #74 Search a 2D Matrix
- leetcode 74: Search a 2D Matrix
- 它怎么又去了。
- 当前商务日语教材的现状及其建设建议
- Java 基础知识汇总 - 02
- 108. Convert Sorted Array to Binary Search Tree Leetcode Python
- Kali系统ssh服务开启
- Leetcode NO.74 Search a 2D Matrix
- 缩略图、图片水印图、文字水印图
- 爬上喜马拉雅的喜悦——Leo谈跑步(1)
- Balanced Binary Tree Leetcode Python
- STM32 学习七 USART通信2 寄存器方式编程
- 青木的书籍,--股票
- LeetCode: Trapping Rain Water
- ping 网段 内 所有的IP 地址
- you must restart adb and eclipse的相关解决办法