Lintcode028.Search a 2D Matrix
Posted Vincent丶
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Lintcode028.Search a 2D Matrix相关的知识,希望对你有一定的参考价值。
题目:
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.
题解:
Solution 1 ()
class Solution { public: /** * @param matrix, a list of lists of integers * @param target, an integer * @return a boolean, indicate whether matrix contains target */ bool searchMatrix(vector<vector<int> > &matrix, int target) { if (matrix.empty() || matrix[0].empty()) { return false; } int rowEnd = matrix.size() - 1; int colEnd = matrix[0].size() - 1; int start = 0, mid = 0; //rowMid while (start + 1 < rowEnd) { mid = start + (rowEnd - start) / 2; if (matrix[mid][0] == target) { return true; } else if (matrix[mid][0] > target) { rowEnd = mid; } else { start = mid; } } int row = 0; if (matrix[start][0] <= target && matrix[start][colEnd] >= target) { row = start; } else if (matrix[rowEnd][0] <= target && matrix[rowEnd][colEnd] >= target) { row = rowEnd; } else { return false; } start = 0; //colMid while (start + 1 < colEnd) { mid = start + (colEnd - start) / 2; if (matrix[row][mid] == target) { return true; } else if (matrix[row][mid] > target) { colEnd = mid; } else { start = mid; } } if(matrix[row][start] == target || matrix[row][colEnd] == target) { return true; } return false; } };
Solution 2 ()
class Solution { public: /** * @param matrix, a list of lists of integers * @param target, an integer * @return a boolean, indicate whether matrix contains target */ bool searchMatrix(vector<vector<int> > &matrix, int target) { if (matrix.empty() || matrix[0].empty()) { return false; } int m = matrix.size(), n = matrix[0].size(); int start = 0; int end = m * n - 1; int mid = 0; while (start + 1 < end) { mid = start + (end - start) / 2; int row = mid / n; int col = mid % n; if (matrix[row][col] == target) { return true; } else if (matrix[row][col] > target) { end = mid; } else { start = mid; } } if (matrix[start / n][start % n] == target) { return true; } else if (matrix[end / n][end % n] == target) { return true; } else { return false; } } };
以上是关于Lintcode028.Search a 2D Matrix的主要内容,如果未能解决你的问题,请参考以下文章
lintcode28- Search a 2D Matrix- easy
Lintcode038.Search a 2D Matrix II