美文网首页
算法挑战100天 - four(easy)

算法挑战100天 - four(easy)

作者: holmes000 | 来源:发表于2020-08-28 15:45 被阅读0次

类别:数组

题目:https://leetcode-cn.com/problems/transpose-matrix/

我的解:时间 O(n2) 空间O(n2)

private int[][] transpose(int[][] A) {
        int[][] result = new int[][];
        for (int i = 0; i < A.length; i++) {
            for (int j = 0; j < A[i].length; j++) {
                if (result == null) {
                    result = new int[A[i].length][A.length];
                }
                int temp = A[i][j];
                result[j][i] = temp;
            }
        }
        return result;
    }

最优解:时间 O(n2) 空间O(n2)

 public int[][] transpose(int[][] A) {
        int R = A.length, C = A[0].length;
        int[][] ans = new int[C][R];
        for (int r = 0; r < R; ++r)
            for (int c = 0; c < C; ++c) {
                ans[c][r] = A[r][c];
            }
        return ans;
    }

差异点:

1.虽然处理方式基本一致;但是我是在循环中慢慢试错考虑的二维数组行列怎么设置;但是最优解是先考虑到二维数组行列变化规则,再去执行;
2.思维方向很重要,决定了你是否高效;

相关文章

网友评论

      本文标题:算法挑战100天 - four(easy)

      本文链接:https://www.haomeiwen.com/subject/fmplsktx.html