LeetCode: Search a 2D Matrix
来源:互联网 发布:linux vi 命令行模式 编辑:程序博客网 时间:2024/05/16 16:08
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 m = matrix.size(); if(m == 0) return false; return binarySearch(0, m-1, target, matrix); }private: bool binarySearch(int start, int end, int target, vector<vector<int> > &matrix) { if(start > end) return false; int mid = (start+end)/2; if(target <= matrix[mid].back() && target >= matrix[mid].front()) { return binarySearch2(0, matrix[mid].size()-1, target, matrix[mid]); } else if(target < matrix[mid].front()) { return binarySearch(start, mid-1, target, matrix); } else { return binarySearch(mid+1, end, target, matrix); } } bool binarySearch2(int start, int end, int target, vector<int> &row) { if(start > end) return false; int mid = (start + end)/2; if(target == row[mid]) return true; else if(target < row[mid]) return binarySearch2(start, mid-1, target, row); else { return binarySearch2(mid+1, end, target, row); } }};
Round 2:
class Solution {public: bool searchMatrix(vector<vector<int> > &matrix, int target) { int l = 0, r = matrix.size()-1; while(l <= r) { int mid = (l+r)/2; if(matrix[mid][0] == target) return true; else if(target >= matrix[mid][0] && target <= matrix[mid][matrix[0].size()-1]) { l = 0, r = matrix[0].size()-1; while(l <= r) { int mid2 = (l+r) /2; if(matrix[mid][mid2] == target) return true; else if(matrix[mid][mid2] < target) l = mid2+1; else r = mid2-1; } return false; } else if(matrix[mid][0] > target) { r = mid-1; } else { l = 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
- 我是一只修理猫-2
- android 修改DatePickerDialog只显示“年月”,去掉“日”显示
- Android--Spinner(下拉列表效果)
- ASIHTTPRequest的startAsynchronous调用EXC_BAD_ACCESS
- 实现通知中心/控制中心等模糊背景的图层
- LeetCode: Search a 2D Matrix
- if __name__ == "__main__":作用
- 我的IT之路,学c++ ~1++
- ADB logcat 过滤方法(抓取日志)
- JavaBean的创建与使用
- 毕业证、报到证、档案、户口、三方协议
- Python2与Python3共存于Windows
- Ubuntu 下NFS按在配置
- On iPad, UIImagePickerController must be presented via UIPopoverController