classSolution{ public: boolfindNumberIn2DArray(vector<vector<int>> &matrix,int target) { if (matrix.empty()) returnfalse; int m = matrix.size(); int n = matrix[0].size(); for (int i=0;i<m;i++) { for (int j=0;j<n;j++) { if (matrix[i][j]==target) { returntrue; } } } returnfalse; } };
classSolution{ public: boolfindNumberIn2DArray(vector<vector<int>> &matrix,int target) { if (matrix.empty()) returnfalse; int n = matrix.size(); int m = matrix[0].size(); for (int i=0;i<n;i++) { int start = 0; int end = m-1; while (end>=start) { int mid = start + (end-start)/2; if (matrix[i][mid]==target) returntrue; if (matrix[i][mid]<target) start = mid+1; if (matrix[i][mid]>target) end = mid-1; } } returnfalse; } };
// 右上角开始查找 classSolution { public: boolfindNumberIn2DArray(vector<vector<int>>& matrix, int target){ if (matrix.empty()) returnfalse; int m = matrix.size(); int n = matrix[0].size(); int i = 0; int j = n - 1; while (i < m && j >= 0) { if (matrix[i][j] == target) { returntrue; } elseif (matrix[i][j] < target) { i++; } elseif (matrix[i][j] > target) { j--; } } returnfalse; } };
// 左下角开始查找 classSolution { public: boolfindNumberIn2DArray(vector<vector<int>>& matrix, int target){ if (matrix.empty()) returnfalse; int m = matrix.size(); int n = matrix[0].size(); int i = m-1; int j = 0; while (i >=0 && j < n) { if (matrix[i][j] == target) { returntrue; } elseif (matrix[i][j] < target) { j++; } elseif (matrix[i][j] > target) { i--; } } returnfalse; } };