稀疏sparsearray数组和队列

本文探讨了如何在编程中使用稀疏数组优化存储大量零值数据的问题,并介绍了队列,特别是数组实现的普通队列与环形队列的区别和实现。通过实例展示了如何在五子棋程序中运用稀疏数组,以及如何处理队列的添加、获取和显示操作,包括空间复用的挑战和解决方案。
摘要由CSDN通过智能技术生成

一、稀疏sparsearray数组

先看一个实际的需求

编写的五子棋程序中,有存盘退出和续上盘的功能。
在这里插入图片描述
**分析问题
因为该二维数组的很多值是默认值0,因此记录了很多没有意义的数据.->稀疏数组。

这里需要先引入一个概念:稀疏数组
基本介绍

  • 当一个数组中大部分元素为0,或者为同一个值的数组时,可以使用稀疏数组来保存该数组。
    稀疏数组的处理方法是:
  1. 记录数组一共有几行几列,有多少个不同的值
  2. 把具有不同值的元素的行列及值记录在一个小规模的数组中,从而缩小程序的规 模

应用实例

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

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

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

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

import java.io.*;

/**
 * @ClassName sparseArr
 * @Description 稀疏数组实例
 * @Author LuKun
 * @Date 2022/7/5 18:20
 * @Version 1.0
 */
public class sparseArr {
    //"src/main/resources/test/array/sparseArr.txt"
    //读取稀疏数组
    public static int[][] loadArr(String path) throws IOException {
        File file = new File(path);
        if(!file.exists())file.createNewFile();
        try (ObjectInputStream oi = new ObjectInputStream(new FileInputStream(path))){
            Object object = oi.readObject();
            int[][] result= (int[][]) object;
            file.delete();
            return result;
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
            return null;
        }
    }
    //存储稀疏数组
    public static void storeArr(int[][] spaAr,String path){
        try(ObjectOutputStream ob = new ObjectOutputStream(new FileOutputStream(path,false))) {
            ob.writeObject(spaAr);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //数组转稀疏数组
    public static int[][] arrToSparse(int[][] two){
        if (two==null)return null;
        int sum=0;
        for (int i = 0; i < two.length; i++) {
            for (int i1 = 0; i1 < two[i].length; i1++) {
                if (two[i][i1]!=0)sum++;
            }
        }
        int[][] resut=new int[sum+1][3];
        resut[0][0]=two.length;
        resut[0][1]=two[0].length;
        resut[0][2]=sum;
        int count=0;
        for (int i = 0; i < two.length; i++) {
            for (int i1 = 0; i1 < two[i].length; i1++) {
                if (two[i][i1]!=0){
                    count++;
                    resut[count][0]=i;
                    resut[count][1]=i1;
                    resut[count][2]=two[i][i1];
                }
            }
        }
        return resut;
    }

    //稀疏数组转数组
    public static int[][] spareToArr(int[][] spare){
        if (spare==null)return null;
        int[][] result=new int[spare[0][0]][spare[0][1]];
        for (int i = 0; i < spare[0][2]; i++) {
            result[spare[i+1][0]][spare[i+1][1]]=spare[i+1][2];
        }
        return result;
    }

    public static void main(String[] args) throws IOException {
        int[][] test =new int[10][10];
        String path="src/main/resources/test/array/sparseArr.txt";
        test[1][2]=1;
        test[2][3]=2;
        for (int[] ints : test) {
            for (int anInt : ints) {
                System.out.print(anInt+"  ");
            }
            System.out.println();
        }
        System.out.println("=================");
        storeArr(arrToSparse(test),path);
        int[][] ints1=loadArr(path);
        for (int[] anInt : ints1) {
            for (int i : anInt) {
                System.out.print(i+"  ");
            }
            System.out.println();
        }
        System.out.println("=================");
        for (int[] anInt : spareToArr(ints1)) {
            for (int i : anInt) {
                System.out.print(i+"  ");
            }
            System.out.println();
        }
    }
}

二、队列

队列介绍

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

1. 数组实现队列(空间不可复用)

  • 队列本身是有序列表,若使用数组的结构来存储队列的数据,则队列数组的声明如下图,其中maxSize是该队列的最大容量。
  • 因为队列的输出、输入是分别从前后端来处理,因此需要两个变量front及rear分别记录队列前后端的下标,front 会随着数据输出而改变,而rear则是随着数据输入而改变,
  • 当我们将数据存入队列时称为”addQueue",addQueue的处理需要有两个步骤:思路分析
    1)将尾指针往后移: rear+1,当front == rear【空】
    2)若尾指针rear小于队列的最大下标maxSize-1,则将数据存入rear所指的数
    组元素中,否则无法存入数据。rear == maxSize-1[队列满]
  • 代码实现
package com.hanshunping.queue;

import lombok.Data;

import java.util.Scanner;

/**
 * @ClassName ArrayQueueDemo
 * @Description TODO
 * @Author LuKun
 * @Date 2022/7/6 19:33
 * @Version 1.0
 */

public class ArrayQueueDemo {
    public void xx(){
        System.out.println("xxx");
    }
    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("e(exit):退出程序");
            System.out.println("a(add):添加数据到队列");
            System.out.println("g(get):从队列取出数据");
            System.out.println("h(head):查看队列头的数据");
            key=scanner.next().charAt(0);
            switch (key){
                case 's':
                    arrayQueue.showQueue();
                    break;
                case 'e':
                    scanner.close();
                    loop=false;
                    break;
                case 'a':
                    System.out.println("请输入一个数: ");
                    int value= scanner.nextInt();
                    arrayQueue.addQueue(value);
                    break;
                case 'g':
                    try {
                        int res = arrayQueue.getQueue();
                        System.out.printf("取出的数据是%d\n",res);
                    }catch (Exception e){
                        System.out.println(e.getMessage());
                    }
                    break;
                case 'h':
                    try {
                        int res = arrayQueue.headQueue();
                        System.out.printf("队列头的数据是%d\n",res);
                    }catch (Exception e){
                        System.out.println(e.getMessage());
                    }
                    break;
                default:break;
            }
        }
        System.out.println("程序退出!");
    }
}
@Data
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++;
        arr[rear]=n;
    }

    public int getQueue() {
        if(isEmpty())throw new RuntimeException("队列为空,获取数据失败!");
        front++;
        return arr[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];
    }
}

局限性

  • 这种实现方式具有很强的局限性
  • 队列存入数据再取出后,原来数据所在的位置虽然没有数据但是也不允许再次存入数据
  • 这里引出环形队列来解决问题
  • 注意这里使用了@Data注解,需要在pom.xml文件中引入依赖
		<dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.22</version>
        </dependency>

2. 基于数组实现环形队列

  • 思路分析
  • 思路如下:
  1. front变量的含义做一个调整:front就指向队列的第一个元素,也就是说arrfront]就是队列的第一个元素front的初始值=o
  2. rear变量的含义做一个调整:rear指向队列的最后一个元素的后一个位置.因为希望空出一个空间做为约定.rear的初始值=o
  3. 当队列满时,条件是(rear +1)% maxSize = front【满】
  4. 对队列为空的条件,rear == front空
  5. 当我们这样分析,队列中有效的数据的个数(rear+ maxSize-front) % maxSize // rear= 1 front=0
package com.hanshunping.queue;

import lombok.Data;

import java.util.Scanner;

/**
 * @ClassName CircleArrayQueueDemo
 * @Description TODO
 * @Author LuKun
 * @Date 2022/7/6 21:41
 * @Version 1.0
 */
public class CircleArrayQueueDemo {
    public static void main(String[] args) {
        CircleArray arrayQueue = new CircleArray(4);//说明设置4,其队列的有效数据最大是3
        char key=' ';//接收用户输入
        Scanner scanner = new Scanner(System.in);
        boolean loop=true;
        while (loop){
            System.out.println("s(show):显示队列");
            System.out.println("e(exit):退出程序");
            System.out.println("a(add):添加数据到队列");
            System.out.println("g(get):从队列取出数据");
            System.out.println("h(head):查看队列头的数据");
            key=scanner.next().charAt(0);
            switch (key){
                case 's':
                    arrayQueue.showQueue();
                    break;
                case 'e':
                    scanner.close();
                    loop=false;
                    break;
                case 'a':
                    System.out.println("请输入一个数: ");
                    int value= scanner.nextInt();
                    arrayQueue.addQueue(value);
                    break;
                case 'g':
                    try {
                        int res = arrayQueue.getQueue();
                        System.out.printf("取出的数据是%d\n",res);
                    }catch (Exception e){
                        System.out.println(e.getMessage());
                    }
                    break;
                case 'h':
                    try {
                        int res = arrayQueue.headQueue();
                        System.out.printf("队列头的数据是%d\n",res);
                    }catch (Exception e){
                        System.out.println(e.getMessage());
                    }
                    break;
                default:break;
            }
        }
        System.out.println("程序退出!");
    }
}
@Data
class CircleArray{
    private int maxSize;//表示数组的最大容量
    //front 变量的含义做一个调整:front 就指向队列的第一个元素,也就是说arr[front]
    //front 的初始值为0
    private int front;
    //rear 变量的含义做一个调整:rear指向队列的最后一个元素的后一个位置。因为希望空出一个空间
    //rear 的初始值为0
    private int rear;
    private int[] arr;//该数据用于存放数组,模拟队列

    public CircleArray(int arrMaxSize){
        maxSize=arrMaxSize;
        arr=new int[maxSize];
    }

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

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

    //添加数据到队列
    public void addQueue(int n){
        if (isFull()){
            System.out.println("队列满,不能加入数据");
            return;
        }
        arr[rear]=n;
        rear=(rear+1)%maxSize;
    }

    public int getQueue() {
        if(isEmpty())throw new RuntimeException("队列为空,获取数据失败!");

        //这里需要分析出front是指向队列的第一个元素
        // 1.先把front对应的值保留到一个临时变量
        // 2.将front后移,考虑取模
        // 3.将临时保存的变量返回
        int value =arr[front];
        front=(front+1)%maxSize;
        return arr[front];
    }
    //求出当前队列有效数据的个数
    public int size(){
        return (rear+maxSize-front)%maxSize;
    }
    public void showQueue(){
        if(isEmpty()){
            System.out.println("队列为空!");
            return;
        }
        for (int i = front; i < front + size(); i++) {
            System.out.printf("arr[%d]=%d\n",i%maxSize,arr[i%maxSize]);
        }
    }

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

}



队列总结:

队列这种数据结构可以说是对数据存取的规则加上了一定的限制,基于数组来实现的话,由于数组大小一般是不可变的,所以环形队列的难点就在于数组空间的复用上,体现在判断队列是否为空、是否满、添加和删除值时头指针和尾指针如何移动等,这些问题的关键点在于解决队列元素在数组尾部添加值到数组头时头尾指针的变化问题。这里在复述一下:(以上方实现代码为准)

  • 非环形队列,头指针指向队列第一个元素的前一个位置,尾指针指向队列中的最后一个元素的位置。头尾指针初始值都为-1实现简单,但空间不能复用
  • 环形队列,头指针指向队列的第一个元素,尾指针指向队列中最后一个元素的后一个位置。头尾指针的初始值都为0,需要注意的是,数组大小为4是队列中能存储的最大数据数为3,即队列大小为数组大小减一。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值