classSolution { boolbigger(vector<vector<int>>& mat, int y, int x){ int dy[4]{-1,0,1,0}, dx[4]{0,1,0,-1}; int n = mat.size(), m = mat[0].size(); for(int i = 0; i < 4; i++) { int ny = y + dy[i], nx = x + dx[i]; if(0 <= ny and ny < n and0 <= nx and nx < m and mat[ny][nx] >= mat[y][x]) { returnfalse; } } returntrue; } public: vector<int> findPeakGrid(vector<vector<int>>& mat){ int n = mat.size(), m = mat[0].size(), i = 0; while(true) { int l = 0, r = m - 1; while(l <= r) { int mid = l + (r - l) / 2; if(mid + 1 < m and mat[i][mid + 1] >= mat[i][mid]) l = mid + 1; elseif(mid - 1 >= 0and mat[i][mid - 1] >= mat[i][mid]) r = mid - 1; elseif(i + 1 < n and mat[i + 1][mid] >= mat[i][mid]) i += 1; elseif(i - 1 >= 0and mat[i - 1][mid] >= mat[i][mid]) i -= 1; elsereturn {i, mid}; } } return {}; } };
classSolution { intgetOrDefault(vector<int>& nums, int i, int def = INT_MIN){ if(i < 0or i >= nums.size()) return def; return nums[i]; } intgetOrDefault(vector<vector<int>>& mat, int y, int x, int def = INT_MIN){ if(0 <= y and y < mat.size()) { return mat[y][x]; } return def; } public: vector<int> findPeakGrid(vector<vector<int>>& mat){ int l = 0, r = mat[0].size(), y = 0; while(true) { int m = l + (r - l) / 2; int left = getOrDefault(mat[y], m - 1); int right = getOrDefault(mat[y], m + 1); if(left < mat[y][m] and mat[y][m] > right) { int up = getOrDefault(mat, y - 1, m); int down = getOrDefault(mat, y + 1, m); if(up < mat[y][m] and mat[y][m] > down) return {y, m}; elseif(up > down) y--; else y++; } elseif (left > right) r = m - 1; else l = m + 1; } return {-1,-1}; } };