[LeetCode OJ]Search a 2D Matrix
来源:互联网 发布:网络加速器 编辑:程序博客网 时间:2024/06/06 00:19
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) { int left = 0; int right = matrix.size()-1; if(left != right) { while(left<=right) { int middle = left + (right-left)/2; if(matrix[middle][0] < target) { left = middle+1; } else if(matrix[middle][0] > target) { right = middle-1; } else { return true; } } } if(right == -1) { return false; } else { int row = right; int left = 0; int right = matrix[row].size()-1; while(left<=right) { int middle = left + (right-left)/2; if(matrix[row][middle] < target) { left = middle+1; } else if(matrix[row][middle] > target) { right = middle-1; } else { return true; } } return false; } }};
还可以直接做,右上角元素开始遍历。
class Solution {public: bool searchMatrix(vector<vector<int> > &matrix, int target) { int i =matrix.size()-1; int j=0; int n = matrix.size(); int m = matrix[0].size(); while(i>=0&&j<m) { if(matrix[i][j]==target) { return true; } else if(matrix[i][j]<target) { j++; } else { i--; } } return false; }};
0 0
- LeetCode OJ:Search a 2D Matrix
- LeetCode OJ - Search a 2D Matrix
- [LeetCode OJ]Search a 2D Matrix
- LeetCode OJ Search a 2D Matrix
- LeetCode OJ | Search a 2D Matrix
- leetcode oj java Search a 2D Matrix
- leetcode oj java Search a 2D Matrix II
- LeetCode OJ-74.Search a 2D Matrix
- LeetCode OJ 240. Search a 2D Matrix II
- [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
- CodeForces 55D Beautiful numbers (数位DP)
- c++开源库大全
- XStream解析xml和json
- OpenCV卷积操作
- java 连接 jdbc
- [LeetCode OJ]Search a 2D Matrix
- Jquery优化
- Android-ActionBar(下)
- 3.工厂方法模式
- Qt打印
- 排序算法之冒泡排序
- unity学习之标签
- iOS调试(iOS Debugging Magic)
- Hibernate(3)关系映射之一对多级联