Leetcode Search a 2D Matrix
来源:互联网 发布:linux ndk 编译的so 编辑:程序博客网 时间:2024/06/01 10:14
题意:给定一个元素按序排列的矩阵,判断某个元素是否在其中。
思路:两次二分搜索,先搜索列,再搜索行。
class Solution {public: bool searchMatrix(vector<vector<int>>& matrix, int target) { if(matrix.size() == 0) return false; if(target < matrix[0][0]) return false; if(target == matrix[0][0]) return true; int low = 0; int high = matrix.size() - 1; if(matrix[low][0] == target || matrix[high][0] == target) return true; while(high - low > 1) { if(matrix[low][0] == target || matrix[high][0] == target) return true; int mid = low + (high -low) / 2; if(matrix[mid][0] == target ) return true; if(target < matrix[mid][0]) { high = mid; } else { low = mid; } } int r = low; if(matrix[high][0] < target) r = high; low = 0; high = matrix[r].size() - 1; while(low != high) { if(matrix[r][low] == target || matrix[r][high] == target) return true; int mid = low + (high - low) / 2; if(matrix[r][mid] == target) return true; if(matrix[r][mid] < target) { low = mid + 1; } else { high = mid; } } if(matrix[r][low] == target) return true; return false; }};
另一种思路是把他当作一维二分查找做。
n * m matrix convert to an array => matrix[x][y] => a[x * m + y]an array convert to n * m matrix => a[x] =>matrix[x / m][x % m];
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
- PHP执行系统外部命令函数:exec()、passthru()、system()、shell_exec()
- Leetcode 448. Find All Numbers Disappeared in an Array
- MyISAM和InnoDB的主要区别和应用场景
- 157. Read N Characters Given Read4
- 第一次项目总结
- Leetcode Search a 2D Matrix
- Spring基础:快速入门spring cloud(1):Spring Cloud介绍
- C++类对象共享数据的两种实现方法
- bias and variance
- Unity-android Remote 测试
- github 传输速度慢解决方法
- 二进制最大公约数算法
- Leetcode Evaluate Reverse Polish Notation
- JavaScript 运动框架 Step by step