02 - 稀疏数组和队列

一、稀疏数组

1. 应用场景和介绍

编写的五子棋程序中,有存盘退出和继续上盘的功能。

image.png
image.png

该二维数组的很多值都是默认值 0,因此记录了很多无意义的数据,所以可以使用稀疏数组来保存该数组。

image.png
image.png
image.png
image.png

稀疏数组的处理方法:

  1. 记录数组一共有几行几列,有多少个不同的值
  2. 把具有不同值的元素的行列及值记录在一个小规模数组中,从而缩小规模
  3. 稀疏数组列数是固定 3 列,行数根据原始二维数组而定

2. 稀疏数组转换的思路

二维数组转稀疏数组:

  1. 遍历原始的二维数组,得到有效数据的个数 sum
  2. 根据 sum 可创建稀疏数组 spareArr int[sum+1][3]
  3. 将二维数组的有效数据存入稀疏数组

稀疏数组转二维数组:

  1. 先读取稀疏数组的第一行,根据第一行的数据,创建原始二维数组,比如刚才的棋盘 newChessArr = int[11][11]
  2. 再读取稀疏数组后几行的数据,并赋值给原始二维数组

3. 代码实现

package com.github.wangpeng1994.datastructure.sparsearray;

public class SparseArray {

    public static void main(String[] args) {
        // 创建一个原始二维数组,如 11x11
        int[][] twoDArr = new int[11][11];
        twoDArr[1][2] = 1;
        twoDArr[2][3] = 2;
        twoDArr[3][0] = 1;

        for (int[] row : twoDArr) {
            for (int data : row) {
                System.out.printf("%d\t", data);
            }
            System.out.println();
        }

        int[][] sparseArr = twoDArr2SparseArr(twoDArr);

        SparseArr2TwoDArr(sparseArr);
    }

    /**
     * 二维数组 转 稀疏数组
     *
     * @param twoDArr 原始二维数组
     * @return 转换后的稀疏数组
     */
    private static int[][] twoDArr2SparseArr(int[][] twoDArr) {
        int rows = twoDArr.length;
        int cols = twoDArr[0].length;

        // 1. 遍历二维数组得到非零数据的总数
        int sum = 0;
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                if (twoDArr[i][j] != 0) {
                    sum++;
                }
            }
        }

        // 2. 创建相应稀疏数组并为第一行赋值
        int[][] sparseArr = new int[sum + 1][3];
        sparseArr[0][0] = rows;
        sparseArr[0][1] = cols;
        sparseArr[0][2] = sum;

        // 3. 再次遍历二维数组将有效数据填充到稀疏数组中
        int count = 0; // 用于记录有效数据在稀疏数组中应处的行数
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                if (twoDArr[i][j] != 0) {
                    count++;
                    sparseArr[count][0] = i;
                    sparseArr[count][1] = j;
                    sparseArr[count][2] = twoDArr[i][j];
                }
            }
        }

        // 输出稀疏数组
        for (int[] row : sparseArr) {
            System.out.printf("%d\t%d\t%d\n", row[0], row[1], row[2]);
        }

        return sparseArr;
    }

    /**
     * 稀疏数组 恢复到 原始二维数组
     *
     * @param sparseArr 稀疏数组
     * @return 原始二维数组
     */
    private static int[][] SparseArr2TwoDArr(int[][] sparseArr) {
        // 1. 读取稀疏数组第一行的数据,创建原始二维数组
        int[][] twoDArr = new int[sparseArr[0][0]][sparseArr[0][1]];

        // 2. 再读取稀疏数组其余行的数据,恢复原始二维数组
        for (int i = 1; i < sparseArr.length; i++) {
            twoDArr[sparseArr[i][0]][sparseArr[i][1]] = sparseArr[i][2];
        }

        // 输出恢复后的二维数组
        for (int[] row : twoDArr) {
            for (int data : row) {
                System.out.printf("%d\t", data);
            }
            System.out.println();
        }
        return twoDArr;
    }
}

二、队列

1. 应用场景和介绍

  • 队列是一个有序列表,可以用数组或者链表来实现
  • 遵循先入先出(FIFO)的原则,即:先存入队列的数据,要先取出;后存入队列的数据要后取出
  • 从尾部存入,从头部取出
image

2. 数组模拟队列

2.1 思路分析

image.png
image.png

队列本身是有序列表,若用数组来模拟,需要定义一些指针和操作时的判断条件。

front:指向队列头部前一个位置,初始值为 -1
rear:指向队列尾部数据,初始值为 -1
判断队列空:rear == front
判断队列满:rear == maxSize - 1
队列有效容量:maxSize

2.2 代码实现

package com.github.wangpeng1994.datastructure.queue;

public class ArrayQueue {
    private int maxSize;
    private int front;
    private int rear;
    private int[] arr;

    public ArrayQueue(int maxSize) {
        this.maxSize = maxSize;
        arr = new int[maxSize];
        front = -1; // 指向队列头部前一个位置
        rear = -1; // 指向队列尾
    }

    // 判断队列是否满
    public boolean isFull() {
        return rear == maxSize - 1;
    }

    // 判断队列是否空
    public boolean isEmpty() {
        return rear == front;
    }

    // 添加数据到队列
    public boolean addQueue(int e) {
        if (isFull()) {
            System.out.println("队列已满,添加失败");
            return false;
        }
        arr[++rear] = e; // rear后移,并从尾部添加数据
        return true;
    }

    // 获取队列数据,出队列
    public int getQueue() {
        if (isEmpty()) {
            throw new RuntimeException("队列为空,没有数据");
        }
        return arr[++front]; // front后移,并从头部取出数据
    }

    // 显示队列的所有数据
    public void showQueue() {
        if (isEmpty()) {
            System.out.println("队列为空,没有数据");
            return;
        }
        for (int i = 0; i < arr.length; i++) {
            System.out.printf("arr[%d]=%d\n", i, arr[i]);
        }
    }

    // 显示队列头部数据,但不取出
    public int headQueue() {
        if (isEmpty()) {
            throw new RuntimeException("队列为空,没有数据");
        }
        return arr[front + 1];
    }
}
package com.github.wangpeng1994.datastructure.queue;

import java.util.Scanner;

public class ArrayQueueDemo {

    public static void main(String[] args) {
        // 测试数组模拟队列基础款
        ArrayQueue queue = new ArrayQueue(4);
        // 测试数组模拟环形队列
        CircleArrayQueue queue = new CircleArrayQueue(4);
        char key = ' '; // 接受用户输入
        Scanner scanner = new Scanner(System.in); // 扫描标准输入
        boolean loop = true;
        // 创建菜单
        while (loop) {
            System.out.println("\ns(show): 显示队列");
            System.out.println("e(exit): 退出程序");
            System.out.println("a(add): 添加数据到队列");
            System.out.println("g(get): 从队列取出数据");
            System.out.println("h(head): 查看队列头部数据\n");
            key = scanner.next().charAt(0); // 等待输入一个字符
            switch (key) {
                case 's':
                    queue.showQueue();
                    break;
                case 'a':
                    System.out.println("输入一个数");
                    int value = scanner.nextInt(); // 等待输入一个数字
                    queue.addQueue(value);
                    break;
                case 'g':
                    try {
                        int res = queue.getQueue();
                        System.out.printf("取出的数据是%d\n", res);
                    } catch (Exception e) {
                        // TODO: handle exception
                        System.out.println(e.getMessage());
                    }
                    break;
                case 'h':
                    try {
                        int res = queue.headQueue();
                        System.out.printf("队列头的数据是%d\n", res);
                    } catch (Exception e) {
                        // TODO: handle exception
                        System.out.println(e.getMessage());
                    }
                    break;
                case 'e':
                    scanner.close();
                    loop = false;
                    break;
                default:
                    break;
            }

        }

        System.out.println("程序退出");
    }
}

3. 数组模拟环形队列

3.2 思路分析

存在的问题和优化方式:

  1. 刚才的实现中,数组使用一次就不能用了,没有达到复用的效果
  2. 把该数组改进成一个环形的队列(通过取模来实现,防止数组越界)

下面使用 数组模拟环形队列来做到重复使用的目的。

front:指向队列头部数据,初始值为 0
rear:指向队列尾部后一个位置,初始值为 0
判断队列空:rear == front
判断队列满:(rear + 1) % maxSize
队列有效容量:maxSize - 1(空出一个位置便于计算)
计算队列中有效数据的个数:(rear + maxSize - front) % maxSize

3.3 代码实现

package com.github.wangpeng1994.datastructure.queue;

public class CircleArrayQueue {
    private int maxSize; // 表示数组最大容量,实际有效数据容量为 maxSize - 1,预留一个空位方便计算
    private int front; // front 指向队列的第一个元素,初始值为 0
    private int rear; // rear 指向队列最后一个元素的后一个位置,初始值为 0
    private int[] arr;

    public CircleArrayQueue(int maxSize) {
        this.maxSize = maxSize;
        arr = new int[maxSize];
    }

    // 判断队列是否满
    public boolean isFull() {
        return (rear + 1) % maxSize == front;
    }

    // 判断队列是否空
    public boolean isEmpty() {
        return rear == front;
    }

    // 添加数据到队列
    public boolean addQueue(int n) {
        if (isFull()) {
            System.out.println("队列已满,添加失败");
            return false;
        }
        // 直接将数据加入
        arr[rear] = n;
        // 将 rear 后移,这里必须考虑取模
        rear = (rear + 1) % maxSize;
        return true;
    }

    // 获取队列数据,出队列
    public int getQueue() {
        if (isEmpty()) {
            throw new RuntimeException("队列为空,没有数据");
        }
        // 直接从 front 取出头部数据
        int value = arr[front];
        // 将 front 后移,
        front = (front + 1) % maxSize;
        return value;
    }

    // 显示队列的所有数据
    public void showQueue() {
        if (isEmpty()) {
            System.out.println("队列为空,没有数据");
            return;
        }
        // 思路:从 front 开始遍历有效的元素
        for (int i = front; i < front + size(); i++) {
            System.out.printf("arr[%d]=%d\n", i % maxSize, arr[i % maxSize]);
        }
    }

    // 求出当前队列有效数据的个数
    public int size() {
        return (rear + maxSize - front) % maxSize;
    }

    // 显示队列头部数据,但不取出
    public int headQueue() {
        if (isEmpty()) {
            throw new RuntimeException("队列为空,没有数据");
        }
        return arr[front];
    }

}
image
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容