1. topic
2. answers
2.1. Method I
Compare from the bottom left corner of the matrix
- Return true if the target value is equal to the current element;
- If the target value is greater than the current element, increase j by 1 and search to the right to exclude the data above this column (all smaller than the current element);
- If the target value is less than the current element, i minus 1, search upward, and exclude the data on the right side of this row (all larger than the current element).
class Solution { public: bool searchMatrix(vector<vector<int>>& matrix, int target) { int i = matrix.size() - 1; int j = 0; while (i >=0 && j < matrix[0].size()) { if (target == matrix[i][j]) return true; else if (target > matrix[i][j]) j++; else i--; } return false; } };
2.2. Method 2
First, we find the first number larger than the target value along the diagonal direction. For example, target value 14, we found that 9 < 14 < 17. Then the elements in the upper left corner and the lower right corner can be excluded. We only need to find the remaining rows in the lower left corner and the remaining columns in the upper right corner.
class Solution { public: bool searchMatrix(vector<vector<int>>& matrix, int target) { int m = matrix.size(); if (m == 0) return false; int n = matrix[0].size(); if (n == 0) return false; if (m == 1) return binary_row_search(matrix, 0, n-1, target); if (n == 1) return binary_col_search(matrix, 0, m-1, target); int square = m <= n ? m : n; int i = 0; for (i = 0; i < square - 1; i++) { if (target == matrix[i][i] || target == matrix[i+1][i+1]) return true; else if (target > matrix[i][i] && target < matrix[i+1][i+1]) break; } for (int row = i+1; row < m; row++) { if (binary_row_search(matrix, row, i, target)) return true; } for (int col = i+1; col < n; col++) { if (binary_col_search(matrix, col, i, target)) return true; } return false; } // Row search bool binary_row_search(vector<vector<int>>& matrix, int row, int end, int target) { int start = 0; while (start <= end) { int mid = start + ((end - start) >> 2); // Move right operation priority is less than add, remember to add brackets!!! if (matrix[row][mid] == target) return true; else if (matrix[row][mid] < target) start = mid + 1; else end = mid - 1; } return false; } // Column search bool binary_col_search(vector<vector<int>>& matrix, int col, int end, int target) { int start = 0; while (start <= end) { int mid = start + ((end - start) >> 2); if (matrix[mid][col] == target) return true; else if (matrix[mid][col] < target) start = mid + 1; else end = mid - 1; } return false; } };
For more highlights, please pay attention to "seniusen"!