稀疏数组和队列

本文最后更新于:2022年12月13日 晚上

稀疏数组和队列

稀疏数组

基本介绍

当一个数组中大部分元素为0,或者为同一个值的数组时,可以使用稀疏数组来保存该数组。

稀疏数组的处理方法是:

  1. 记录数组一共有几行几列,有多少个不同的值
  2. 把具有不同值的元素的行列及值记录在一个小规模的数组中,从而缩小程序的规模

sparse_array

实现思路

sparse_array_imp

二维数组转稀疏数组的思路

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

稀疏数组转原始的二维数组的思路

  1. 先读取稀疏数组的第一行,根据第一行的数据,创建原始的二维数组,比如上面的 chessArr2=int[11][11]
  2. 再读取稀疏数组后几行的数据,并赋给原始的二维数组即可.

代码实现

public class SparseArray {
    public static void main(String[] args) {
        // 创建一个原始的二维数组 11*11
        // 0:表示没有棋子,1 表示 黑子, 2 表示 白子
        int[][] chessArr1 = new int[11][11];
        chessArr1[1][2] = 1;
        chessArr1[2][3] = 2;
        chessArr1[5][4] = 2;
        // 输出原始的二维数组
        System.out.println("原始的二维数组");
        for (int[] row : chessArr1) {
            for (int data : row) {
                System.out.printf("%d\t", data);
            }
            System.out.println();
        }
        // 将二维数组转为稀疏数组
        // 1. 遍历原始的二维数组,得到有效数据的个数sum
        int sum = 0;
        for (int i = 0; i < 11; i++) {
            for (int j = 0; j < 11; j++) {
                if (chessArr1[i][j] != 0) {
                    sum++;
                }
            }
        }
        System.out.println(sum);
        // 2. 根据 sum 就可以创建稀疏数组 sparseArr int[sum+1][3]
        int[][] sparseArr = new int[sum + 1][3];
        // 3. 将二维数组的有效数据数据存入到稀疏数组
        sparseArr[0][0] = 11;
        sparseArr[0][1] = 11;
        sparseArr[0][2] = sum;

        // 遍历二维数组,将非O的值存放到sparseArr中
        int count = 1;
        for (int i = 0; i < 11; i++) {
            for (int j = 0; j < 11; j++) {
                if (chessArr1[i][j] != 0) {
                    sparseArr[count][0] = i;
                    sparseArr[count][1] = j;
                    sparseArr[count][2] = chessArr1[i][j];
                    count++;
                }
            }
        }
        // 输出稀疏数组
        System.out.println("稀疏数组");
        for (int[] row : sparseArr) {
            for (int data : row) {
                System.out.printf("%d\t", data);
            }
            System.out.println();
        }
        // 将sparseArr 写入磁盘
        try {
            OutputStream out = new FileOutputStream("map.data");
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(out);
            objectOutputStream.writeObject(sparseArr);
            out.close();
            objectOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 将sparseArr 从磁盘中读取
        int[][] sparseArr2 = null;
        try {
            InputStream in = new FileInputStream("map.data");
            ObjectInputStream objectInputStream = new ObjectInputStream(in);
            Object obj = objectInputStream.readObject();
            sparseArr2 = (int[][]) obj;
            in.close();
            objectInputStream.close();
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
        // 稀疏数组转原始的二维数组
        // 1. 先读取稀疏数组的第一行,根据第一行的数据,创建原始的二维数组,比如上面的 chessArr2=int[11][11]
        assert sparseArr2 != null;
        int[][] chessArr2 = new int[sparseArr2[0][0]][sparseArr2[0][1]];

        for (int i = 1; i < sparseArr.length; i++) {
            chessArr2[sparseArr2[i][0]][sparseArr2[i][1]] = sparseArr2[i][2];
        }
        System.out.println("还原的二维数组");
        for (int[] row : chessArr2) {
            for (int data : row) {
                System.out.printf("%d\t", data);
            }
            System.out.println();
        }
    }
}

队列

基本介绍

  1. 队列是一个有序列表,可以用数组或是链表来实现。
  2. 遵循先入先出的原则。即:先存入队列的数据,要先取出。后存入的要后取出

数组模拟队列

实现思路

  • 队列本身是有序列表,若使用数组的结构来存储队列的数据,则队列数组的声明如下图,其中maxSize是该队列的最大容量。
  • 因为队列的输出、输入是分别从前后端来处理,因此需要两个变量front及rear分别记录队列前后端的下标,front会随着数据输出而改变,而rear则是随着数据输入而改变,

queue

当我们将数据存入队列时称为”addQueue”,addQueue的处理需要有两个步骤:

  1. 将尾指针往后移:rear+1,当front == rear(空)
  2. 若尾指针rear小于队列的最大下标maxSize-1,则将数据存入rear所指的数组元素中,否则无法存入数据。rear == maxSize-1(队列满)

代码实现

public class ArrayQueueDemo {
    public static void main(String[] args) {

        //创建队列
        ArrayQueue arrayQueue = new ArrayQueue(3);
        char key = ' '; // 接收用户·输入
        Scanner scanner = new Scanner(System.in);
        boolean loop = true;
        // 输出菜单
        while (loop) {
            System.out.println("s(show): 显示队列");
            System.out.println("a(add): 添加元素");
            System.out.println("g(get): 取出元素");
            System.out.println("h(head): 查看头部");
            System.out.println("e(exit): 退出程序");
            key = scanner.next().charAt(0); // 接收一个字符
            switch (key) {
                case 's':
                    arrayQueue.showQueue();
                    break;
                case 'a':
                    System.out.println("输入一个数字");
                    int value = scanner.nextInt();
                    arrayQueue.addQueue(value);
                    break;
                case 'g':
                    try {
                        int res = arrayQueue.getQueue();
                        System.out.println("取出的数据是" + res);
                    } catch (Exception e) {
                        System.out.println(e.getMessage());
                    }
                    break;
                case 'h':
                    try {
                        int res = arrayQueue.headQueue();
                        System.out.println("取出的队列头数据是" + res);
                    } catch (Exception e) {
                        System.out.println(e.getMessage());
                    }
                    break;
                case 'e':
                    scanner.close();
                    loop = false;
                    break;
                default:
                    break;
            }
        }
        System.out.println("程序退出");
    }
}

// 使用数组模拟队列
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 void addQueue(int n) {
        //判断队列是否为满
        if (isFull()) {
            System.out.println("该队列已满,无法添加数据");
            return;
        }
        rear++; // rear后移
        arr[rear] = n;
    }

    //获取队列的数据,出队列
    public int getQueue() {
        if (isEmpty()) {
            //抛出异常
            throw new RuntimeException("队列空,无法取出数据");
        }
        front++;
        return arr[front];
    }

    //显示队列所有数据
    public void showQueue() {
        if (isEmpty()) {
            //抛出异常
            throw new RuntimeException("队列空,无法取出数据");
        }
        //遍历
        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];
    }
}

存在问题

目前数组使用一次就不能用,没有达到复用的效果

优化思路

将这个数组使用算法改进成一个环形的数组

数组模拟环形队列

思路分析

  1. front变量的含义:front就指向队列的第一个元素,也就是说arr[front]就是队列的第一个元素,front的初始值=0
  2. rear变量的含义:rear指向队列的最后一个元素的后一个位置,因为需要空出一个空间做为约定,rear的初始值=0
  3. 当队列满时,条件是(rear+1)%maxSize=front
  4. 对队列为空的条件是rear=front
  5. 队列中有效的数据的个数(rear+maxSize-front)%maxSize

circleQueue

代码实现

public class CircleQueueDemo {
    public static void main(String[] args) {
        CircleQueue circleQueue = new CircleQueue(6);
        char key = ' '; // 接收用户·输入
        Scanner scanner = new Scanner(System.in);
        boolean loop = true;
        // 输出菜单
        while (loop) {
            System.out.println("s(show): 显示队列");
            System.out.println("a(add): 添加元素");
            System.out.println("g(get): 取出元素");
            System.out.println("h(head): 查看头部");
            System.out.println("e(exit): 退出程序");
            key = scanner.next().charAt(0); // 接收一个字符
            switch (key) {
                case 's':
                    circleQueue.showQueue();
                    break;
                case 'a':
                    System.out.println("输入一个数字");
                    int value = scanner.nextInt();
                    circleQueue.addQueue(value);
                    break;
                case 'g':
                    try {
                        int res = circleQueue.removeQueue();
                        System.out.println("取出的数据是" + res);
                    } catch (Exception e) {
                        System.out.println(e.getMessage());
                    }
                    break;
                case 'h':
                    try {
                        int res = circleQueue.headQueue();
                        System.out.println("取出的队列头数据是" + res);
                    } catch (Exception e) {
                        System.out.println(e.getMessage());
                    }
                    break;
                case 'e':
                    scanner.close();
                    loop = false;
                    break;
                default:
                    break;
            }
        }
        System.out.println("程序退出");
    }
}

class CircleQueue {
    private int front;
    private int rear;
    private int maxSize;
    private int[] arr;

    // 初始化环形数组
    public CircleQueue(int maxSize) {
        this.maxSize = maxSize;
        arr = new int[maxSize];
        front = 0;
        rear = 0;
    }

    public boolean isFull() {
        return (rear + 1) % maxSize == front;
    }

    public boolean isEmpty() {
        return rear == front;
    }

    public void addQueue(int num) {
        if (isFull()) {
            System.out.println("队列已满,无法添加");
            return;
        }
        arr[rear] = num;
//        if (rear < maxSize - 1) {
//            rear++;
//        } else {
//            rear = 0;
//        }
        rear = (rear + 1) % maxSize;
    }

    public int removeQueue() {
        if (isEmpty()) {
            System.out.println("队列为空,无法出队");
            return -1;
        }
        int res = arr[front];
//        if (front < maxSize - 1) {
//            front++;
//        } else {
//            front = 0;
//        }
        front = (front + 1) % maxSize;
        return res;
    }

    //显示队列所有数据
    public void showQueue() {
        if (isEmpty()) {
            System.out.println("队列为空,无法显示所有数据");
            return;
        }
        //遍历
        for (int i = front; i < front + getSize(); i++) {
            System.out.printf("arr[%d]=%d\n", i % maxSize, arr[i % maxSize]);
        }
    }


    public int headQueue() {
        if (isEmpty()) {
            System.out.println("队列为空,无法获取头部");
            return -1;
        }
        return arr[front];
    }


    public int getSize() {
        return (rear + maxSize - front) % maxSize;
    }
}

稀疏数组和队列
https://yorick-ryu.github.io/数据结构/数据结构_稀疏数组和队列/
作者
Yorick
发布于
2022年6月25日
许可协议