LeetCode 54 - Spiral Matrix

校招时刷题误区

1. AC后上传到Github就不管了

性价比很低,别人的solution不代表自己真正消化理解了,刷完不总结反思很容易遗忘,以致看submissions只记得自己AC过,而思路完全记不得。以后每周/双周/月,对最近AC的题目进行白板编程复习,温故而知新,检测标准就是做过的题目白板bug-free AC。

2. 测试用例类型未完全覆盖

坚持防御性编程上来先考虑corner case有哪几类,比如此题必然要考虑好行向量、列向量,方阵,普通矩阵。另外,挖掘出题目潜在的点,比如此题有对称性等。

总结与反思

自己的AC Solution
class Solution {
    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> result = new ArrayList<>();
        if (matrix == null || matrix.length == 0) {
            return result;
        }
        int m = matrix.length, n = matrix[0].length;
        for (int k = 0; k < (Math.min(m, n) + 1) / 2; ++k) {
            int j = 0;
            for (j = k; j < n - k; ++j) {
                result.add(matrix[k][j]);
            }
            for (j = k + 1; j < m - k; ++j) {
                result.add(matrix[j][n - k - 1]);
            }
            if (m - k - 1 > k) {
                for (j = n - k - 2; j >= k; --j) {
                    result.add(matrix[m - k - 1][j]);
                }
            }
            if (n - k - 1 > k){
                for (j = m - k - 2; j > k; --j) {
                    result.add(matrix[j][k]);
                }
            }
        }
        return result;
    }
}
九章的Solution
class Solution {
    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> result = new ArrayList<>();
        if (matrix == null || matrix.length == 0) {
            return result;
        }
        int m = matrix.length, n = matrix[0].length;
        int x = 0, y = 0;
        while (m > 0 && n > 0) {
            if (m == 1) {
                for (int i = 0; i < n; ++i) {
                    result.add(matrix[x][y++]);
                }
                break;
            } else if (n == 1) {
                for (int i = 0; i < m; ++i) {
                    result.add(matrix[x++][y]);
                }
                break;
            }
            for (int i = 0; i < n - 1; ++i) {
                result.add(matrix[x][y++]);
            }
            for (int i = 0; i < m - 1; ++i) {
                result.add(matrix[x++][y]);
            }
            for (int i = 0; i < n - 1; ++i) {
                result.add(matrix[x][y--]);
            }
            for (int i = 0; i < m - 1; ++i) {
                result.add(matrix[x--][y]);
            }
            x++;
            y++;
            m = m - 2;
            n = n - 2;
        }
        return result;
    }
}
总结与反思

虽然自己写的AC code更短,但更像是外行通过观察规律写出的code。九章的算法更符合计算机思维,通过 ( x , y ) (x,y) 记录起始点坐标,通过 m m n n 控制步数,在面试时更容易bug-free的写出来。自己的code万一面试时忘记一个 i f if 就直接gg了。

另外记一些鬼才/不常见的思路,在面试时是有风险的,不是所有面试官都像Pony.ai有ACM大神坐镇,能迅速理解你的思路,大多数公司面试官都是业务线开发临时准备。所以稳妥起见,熟练掌握通用思路是第一顺位。

发布了11 篇原创文章 · 获赞 2 · 访问量 667

猜你喜欢

转载自blog.csdn.net/liheng301/article/details/104946578
今日推荐