[leetcode]Search a 2D Matrix
来源:互联网 发布:财务金融知乎 编辑:程序博客网 时间:2024/04/30 23:24
问题描述:
Write an efficient algorithm that searches for a value in anm 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
, returntrue
.
基本思路:
二分查找。
代码:
bool searchMatrix(vector<vector<int> > &matrix, int target) { //C++ int rows = matrix.size(); if(rows == 0) return false; int cols = matrix[0].size(); int low = 0, high = rows*cols-1; int i,j; while(low <= high) { int mid = (low + high)/2; i = mid/cols; j = mid%cols; if(matrix[i][j] == target) return true; if(matrix[i][j] < target) low = mid +1; else high = mid -1; } return false; }
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
- ngxin的Module开发(2)
- asp.net 弹出窗口 单击确定和取消跳转到指定页面
- 让apache产生cookie并记录到日志
- C#连接MYSQLSQEVE数据库示例代码
- tiff与tfw
- [leetcode]Search a 2D Matrix
- nginx源码分析--module开发(3)
- 用js模拟struts2的多action调用
- 截获或替换linux系统调用
- centos配置静态或动态的IP地址呢?
- 结构的简单实用
- 机器码作为shellcode运行时段错误
- python处理多行文件内容
- Context-----Activity,Application之间的交流使者