[LeetCode]Search a 2D Matrix
2013-06-01 09:45
274 查看
class Solution { //binary search at the last column first, find the interested row //then binary search in this row public: bool searchMatrix(vector<vector<int> > &matrix, int target) { // Start typing your C/C++ solution below // DO NOT write int main() function int rowNum = matrix.size(); if(0 == rowNum) return false; int colNum = matrix[0].size(); //get the row int l = 0; int r = rowNum-1; while (l <= r)//find the first first element bigger than target { int m = l+(r-l)/2; if (matrix[m][colNum-1] == target) return true; else if (matrix[m][colNum-1] < target) l = m+1; else// if ((matrix[m][colNum-1] > target) r = m-1; } int row = l; if(row < 0 || row >= rowNum) return false; l = 0; r = colNum-1; while (l <= r) { int m = l+(r-l)/2; if (matrix[row][m] == target) return true; else if (matrix[row][m] < target) l = m+1; else// if ((matrix[m][colNum-1] > target) r = m-1; } return false; } };
second time
class Solution { public: int searchRow(vector<vector<int> > &matrix, int target) { int rowNum = matrix.size(); int colNum = matrix[0].size(); int left = 0; int right = rowNum-1; while(left <= right) { int mid = left+(right-left)/2; int curNum = matrix[mid][colNum-1]; if(curNum == target) return mid; else if(curNum > target) right = mid-1; else left = mid+1; } if(left >= 0 && left < rowNum && matrix[left][colNum-1] >= target) return left; else return false; } int searchColumn(vector<vector<int> > &matrix, int rowIdx, int target) { int rowNum = matrix.size(); int colNum = matrix[0].size(); int left = 0; int right = colNum-1; while(left <= right) { int mid = left+(right-left)/2; int curNum = matrix[rowIdx][mid]; if(curNum == target) return mid; else if(curNum > target) right = mid-1; else left = mid+1; } return -1; } bool searchMatrix(vector<vector<int> > &matrix, int target) { // Start typing your C/C++ solution below // DO NOT write int main() function int n = matrix.size(); if(n == 0) return false; int m = matrix[0].size(); if(m == 0) return false; int rowIdx = searchRow(matrix, target); if(rowIdx == -1) return false; int columnIdx = searchColumn(matrix, rowIdx, target); if(columnIdx == -1) return false; return true; } };
相关文章推荐
- 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 2D矩阵查找 解题报告
- [LeetCode] Search a 2D Matrix
- 二维数组中的查找(LeetCode: 74. Search a 2D Matrix)
- 【LeetCode】Search a 2D Matrix & Set Matrix Zeroes & Spiral Matrix & Spiral Matrix II
- (leetcode)Search a 2D Matrix
- Leetcode 74. Search a 2D Matrix
- LeetCode:Search a 2D Matrix
- LeetCode--search-a-2d-matrix
- 【Leetcode】74. Search a 2D Matrix
- 【leetcode】【74】Search a 2D Matrix
- 【LeetCode】C# 74、Search a 2D Matrix
- Leetcode NO.74 Search a 2D Matrix
- LeetCode_74 Search a 2D Matrix
- leetcode 240: Search a 2D Matrix II C++Version
- Search a 2D Matrix leetcode java
- Leetcode: Search a 2D Matrix