【LeetCode】74. Search a 2D Matrix
来源:互联网 发布:excel怎么求数据的方差 编辑:程序博客网 时间:2024/06/06 01:15
题目描述
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
.
解题思路
二分查找
先对行进行二分查找,找到比目标小一点的数字。
再对找到的行进行列的二分查找。
AC代码
class Solution {public: bool searchMatrix(vector<vector<int>>& matrix, int target) { int m = matrix.size(); if (!m) return false; int n = matrix[0].size(); if (!n) return false; //binary search for row index int begin = 0, end = m - 1; int mid; while (begin < end) { mid = (begin + end) / 2 + 1; if (matrix[mid][0] == target) return true; if (matrix[mid][0] < target) begin = mid; else end = mid - 1; } int i = begin; //binary search for column begin = 0; end = n; while (begin < end) { mid = (begin + end) / 2; if (matrix[i][mid] == target) return true; if (matrix[i][mid] < target) begin = mid + 1; else end = mid; } return false; }};
0 0
- 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
- 74. Search a 2D Matrix LeetCode
- [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-74. Search a 2D Matrix
- [leetcode] 74. Search a 2D Matrix
- |BZOJ 1619|搜索|[Usaco2008 Nov]Guarding the Farm 保卫牧场
- namespace的作用
- 利用先序、后序、中序两两组合重构二叉树(以Java为例)
- final的神奇功能
- HDOJ 1272 小希的迷宫(基础并查集)
- 【LeetCode】74. Search a 2D Matrix
- 使用reaver命令穷举PIN码破解WPA2-PSK加密的无线网络
- Semaphore的使用之方法tryAcquire()的使用
- leetcode 169. Majority Element python
- C语言结构体数组
- JAVA继承和接口
- java 代理模式
- 桩模块和驱动模块
- 使用malloc为指针分配内存空间