Search a 2D Matrix -- leetcode
来源:互联网 发布:平时穿冲锋衣 知乎 编辑:程序博客网 时间:2024/06/07 12:50
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
.
基本思路:
1. 先用折半查找,定位到行。
2. 再用折半查找,定位到列。
这里用到的是二段式,二分法查找, 即循环中,只有2个分支,省掉 判等的分支。
在第一次二分退出循环后,需要判断,待查找值,位于当前行前,或者是前一行。
class Solution {public: bool searchMatrix(vector<vector<int> > &matrix, int target) { if (matrix.empty() || matrix[0].empty()) return false; int low = 0, high = matrix.size()-1; while (low < high) { const int mid = low + (high - low) / 2; if (matrix[mid][0] < target) low = mid + 1; else high = mid; } const int row = low && matrix[low][0] > target ? low - 1: low; low = 0, high = matrix[row].size()-1; while (low < high) { const int mid = low + (high - low) / 2; if (matrix[row][mid] < target) low = mid + 1; else high = mid; } return matrix[row][low] == target; }};
此题可以把二维数组,当成一个一维有序数组进行折半查找。
但需要一个将一维坐标,转换成二维坐标的过程。 将需要额外进/和%的运算。
0 0
- [leetcode][Search] Search a 2D Matrix
- LeetCode: Search a 2D Matrix
- LeetCode Search a 2D Matrix
- [Leetcode] Search a 2D Matrix
- LeetCode : Search a 2D Matrix
- [LeetCode] Search a 2D Matrix
- Leetcode 74 Search a 2D Matrix
- leetcode 90: Search a 2D Matrix
- [LeetCode]Search a 2D Matrix
- [Leetcode] Search a 2-D matrix
- [Leetcode]Search a 2D Matrix
- [leetcode]Search a 2D Matrix
- LeetCode-Search a 2D Matrix
- [leetcode] Search a 2D Matrix
- LeetCode - Search a 2D Matrix
- LeetCode:Search a 2D Matrix
- LeetCode 74: Search A 2D Matrix
- leetcode之Search a 2D Matrix
- cplusplus第2章
- Android性能优化系列——Profile GPU Rendering
- Android -- 获取CPU使用率
- AndroidStudio dexDebug错误
- 进程系统调用——fork函数深入理解
- Search a 2D Matrix -- leetcode
- 如何在整个项目中构造一个通用的共享的唯一的对象
- Cocos2d-3.x_保存数据和读取数据
- linux 可执行文件创建 学习笔记
- arm linux学习之路 1
- Java中的基本数据类型和引用数据类型的内存模型
- Android Studio 引用工程
- xml概述
- js 正则判断数字合法性