【算法练习】数组操作

二维数组顺时针旋转

解决思路

  1. 创建新数组,将原数组的数据按照一定的顺序放入新数组中。
  2. 如果是顺时针的话,原数组中第一排的元素是应该放在新数组最后一列中的。

Java实现

java 复制代码
public class RotateOne {

    public static void main(String[] args) {
        int[][] A = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
        int n = 3;
        int[][] B = new int[n][n];
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                B[j][n - 1 - i] = A[i][j];
            }
        }
        ArrayUtil.printArray(B);
    }
}

二维数组逆时针旋转

解决思路

  1. 逆时针的话,原数组第一排的元素放在新数组的第一列

Java实现

java 复制代码
public class RotateTwo {

    public static void main(String[] args) {
        int[][] A = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
        int n = 3;
        int[][] B = new int[n][n];
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                B[n - 1 - j][i] = A[i][j];
                //A[0][0]-->B[2][0]
                //A[0][1]-->B[1][0]
            }
        }
        ArrayUtil.printArray(B);
    }
}

螺旋矩阵

https://leetcode.cn/problems/spiral-matrix/

解决思路

  1. 设定数组的边界,并且不断的更新边界值。
  2. 跳出循环的条件,当更新边界值不满足条件的时候,跳出循环。

Java实现

java 复制代码
class Solution_LC54_II {
    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> res = new ArrayList<>();
        if (matrix.length == 0) {
            return res;
        }

        int top = 0, bottom = matrix.length - 1, left = 0, right = matrix[0].length - 1;
        while (true) {
            for (int i = left; i <= right; i++) {
                res.add(matrix[top][i]);
            }
            if (++top > bottom) {
                break;
            }
            for (int i = top; i <= bottom; i++) {
                res.add(matrix[i][right]);
            }
            if (--right < left) {
                break;
            }
            for (int i = right; i >= left; i--) {
                res.add(matrix[bottom][i]);
            }
            if (--bottom < top) {
                break;
            }
            for (int i = bottom; i >= top; i--) {
                res.add(matrix[i][left]);
            }
            if (++left > right) {
                break;
            }
        }
        return res;
    }
}
相关推荐
Christo32 分钟前
TKDE-2026《Efficient Co-Clustering via Bipartite Graph Factorization》
人工智能·算法·机器学习·数据挖掘
2401_838472513 分钟前
C++异常处理最佳实践
开发语言·c++·算法
m0_736919107 分钟前
C++中的类型标签分发
开发语言·c++·算法
2301_7903009613 分钟前
C++与微服务架构
开发语言·c++·算法
重生之我是Java开发战士19 分钟前
【优选算法】前缀和:一二维前缀和,寻找数组的中心下标,除自身以外数组的乘积,和为K的子数组,和可被K整除的子数组,连续数组,矩阵区域和
线性代数·算法·矩阵
梵刹古音22 分钟前
【C语言】 循环结构
c语言·开发语言·算法
皮皮哎哟29 分钟前
冒泡排序与数组传递全解析 一维二维指针数组及二级指针应用指南
c语言·算法·冒泡排序·二维数组·指针数组·传参·二级指针
m0_5613596730 分钟前
C++代码冗余消除
开发语言·c++·算法
近津薪荼41 分钟前
优选算法——滑动窗口1(单调性)
c++·学习·算法
diediedei43 分钟前
嵌入式C++驱动开发
开发语言·c++·算法