标签:get previous target ram while wmi int val log
题目:
Write an efficient algorithm that searches for a value in an m x n matrix.
This matrix has the following properties:
题解:
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; } } };
【Lintcode】028.Search a 2D Matrix
标签:get previous target ram while wmi int val log
原文地址:http://www.cnblogs.com/Atanisi/p/6821759.html