LeetCode | 74. Search a 2D Matrix
2017-08-10 21:49
495 查看
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.
思路:二分,复杂度O(log(m+n))
代码二:将矩阵展开,当做一个有序列表,然后直接查找
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.
思路:二分,复杂度O(log(m+n))
Solution
代码一:先对行二分,再对列二分class Solution { public: bool searchMatrix(vector<vector<int>>& matrix, int target) { int row = -1, col = -1; int m = matrix.size(); if(m == 0) return false; int n = matrix[0].size(); if(n == 0) return false; //先找在哪一行 int left = 0, right = m-1; while(left <= right) { int mid = (left+right)/2; if(matrix[mid][0] > target) right = mid-1; else { if(mid == m-1) //已经是最后一行 { row = mid; break; } else if(matrix[mid+1][0] > target) { row = mid; break; } else left = mid+1; } } if(row == -1) return false; left = 0; right = n-1; while(left <= right) { int mid = (left+right)/2; if(matrix[row][mid] == target) { col = mid; break; } else if(matrix[row][mid] > target) right = mid-1; else left = mid+1; } if(col == -1) return false; return true; } };
代码二:将矩阵展开,当做一个有序列表,然后直接查找
class Solution { public: bool searchMatrix(vector<vector<int> > &matrix, int target) { int n = matrix.size(); if(n == 0) return false; int m = matrix[0].size();\ if(m == 0) return false; int l = 0, r = m * n - 1; while (l != r){ int mid = (l + r - 1) >> 1; if (matrix[mid / m][mid % m] < target) l = mid + 1; else r = mid; } return matrix[r / m][r % m] == target; } };
相关文章推荐
- [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(Java)
- 【Leetcode】74. Search a 2D Matrix
- LeetCode||74. Search a 2D Matrix
- LeetCode 74. Search a 2D Matrix(二维矩阵查找)
- leetcode.array--74. Search a 2D Matrix
- leetcode题解-73. Set Matrix Zeroes && 74. Search a 2D Matrix
- LeetCode-74. Search a 2D Matrix
- 【LeetCode】74. Search a 2D Matrix 解题报告(Python)
- [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
- leetcode题解c++ | 74. Search a 2D Matrix
- [LeetCode] 74. Search a 2D Matrix
- leetcode - 74.Search a 2D Matrix