Skip to content

Instantly share code, notes, and snippets.

@jianminchen
Created February 6, 2018 06:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jianminchen/cc69593d7c07a355a764b0fc9986ac46 to your computer and use it in GitHub Desktop.
Save jianminchen/cc69593d7c07a355a764b0fc9986ac46 to your computer and use it in GitHub Desktop.
Spiral matrix - mock interview - good performance, but less flexible to think about alternative idea.
class Solution {
public static void main(String[] args) {
}
int[] printMatrix(int[][] m) {
int nRows = m.length;
if (nRows < 1) return new int[0];
int nCols = m[0].length;
int[] result = new int[nRows * nCols];
int iRowBegin = 0;
int iColBegin = 0;
int iRowEnd = nRows - 1;
int iColEnd = nCols - 1;
int iR = 0;
while (true) { // whole one circle
for (int i = iColBegin; i<= iColEnd; i++) {
result[iR++] = m[iRowBegin][i];
}
iRowBegin++;
for (int i = iRowBegin; i <= iRowEnd; i++) {
result[iR++] = m[i][iColEnd];
}
iColEnd--;
}
}
//.... stop here. The code is perfect, bug free, very clean.
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment