74. Search a 2D Matrix
来源:互联网 发布:java excel预览 编辑:程序博客网 时间:2024/06/10 22:25
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
.
思路:二分查找。先查找所在行,再查找所在列。
class Solution {public:bool searchMatrix(vector<vector<int>>& matrix, int target) {if (matrix.empty())return false;const int LINE = matrix.size();const int COLUMN = matrix[0].size();int low = 0;int high = matrix.size()-1;int mid;while (low <= high){mid = (low + high) / 2;int tmp = matrix[mid][0];if (tmp == target){return true;}else if(tmp > target){high = mid - 1;}else{if (mid + 1 < LINE && matrix[mid + 1][0] <= target){low = mid + 1;}else{break;}}}low = 0;high = COLUMN - 1;while (low <= high){int middle = (low + high) / 2;int tmp = matrix[mid][middle];if (tmp == target)return true;else if (matrix[mid][middle] > target){high = middle - 1;}else{low = middle + 1;}}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
- 74. Search a 2D Matrix
- 74. Search a 2D Matrix
- Leetcode 74. Search a 2D Matrix
- [LeetCode]74. Search a 2D Matrix
- 74. Search a 2D Matrix LeetCode
- 74. Search a 2D Matrix
- 74. Search a 2D Matrix
- 74. Search a 2D Matrix
- [LeetCode]74. Search a 2D Matrix
- [LeetCode]74. Search a 2D Matrix
- 74. Search a 2D Matrix
- 74. Search a 2D Matrix
- leetcode 74. Search a 2D Matrix
- Knowledge-Based Textual Inference via Parse-Tree Transformations 翻译
- ubuntu 16.04 LTS 系统中配置svn服务器
- 嵌入式LAB 1:启动
- 设计模式——迭代模式
- jquery easyui combotree
- 74. Search a 2D Matrix
- Picasso源码分析(五):into方法追本溯源和责任链模式创建BitmapHunter
- FFT核Modelsim仿真
- springmvc整合redis
- JavaScript内存泄露的4种方式及如何避免
- Python 学习笔记(for循环)
- android图形系统详解六:View layer
- 核心模块,事件驱动-03
- 网络编程---TCP