1. 程式人生 > 其它 >資料結構--稀疏陣列和佇列

資料結構--稀疏陣列和佇列

最近在學尚矽谷的資料結構,特此開一篇blog來做筆記

稀疏陣列

當一個數組中大部分元素是0時,或者為同一個值的陣列時,可以用稀疏陣列來儲存該陣列,節省儲存空間(二維陣列儲存太浪費空間了)

應用場景

  • 五子棋、圍棋記錄黑白子,無佔位處記為0,黑白分別記為1,2
  • 掃雷
  • 象棋類,跳棋等

處理方法:

  • 記錄陣列有幾行幾列,有多少個不同的值
  • 把有不同值的元素的行列及值記錄在一個小規模的數組裡,從而縮小程式的規模

二維陣列轉化稀疏陣列的思路

  • 遍歷原始二維陣列,得到有效資料的個數
  • 根據sum就可以建立稀疏陣列 int spareseArr[sum + 1][3]
  • 將二維陣列的有效資料的個數sum存入稀疏陣列

稀疏陣列轉原始二維陣列

  • 先讀稀疏陣列第一行,根據第一行資料建立原始二維陣列
  • 在讀取稀疏陣列後幾行的資料,並賦予原始的二維陣列int originArr[size][size]即可

程式碼

//spareseArray.java
import java.util.Scanner;
public class spareseArray{
    public static void main(String[] args){
        public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int size = scan.nextInt();
        scan.close();
        int chessArr[][] = new int[size][size];//建立一個11*11的棋盤
        chessArr[1][2] = 1;
        chessArr[2][3] = 2;
        chessArr[4][6] = 1;
        int sum = 0;
        for (int i = 0; i < size; i++) {
            for (int j = 0; j < size; j++) {
                if (chessArr[i][j] != 0)
                    sum++;
            }
        }
        //建立稀疏陣列
        int spareseArr[][] = new int[sum + 1][3];
        //給稀疏陣列賦值
        spareseArr[0][0] = size;
        spareseArr[0][1] = size;
        spareseArr[0][2] = sum;
        //遍歷二維陣列,把非0的值存放在稀疏陣列中
        int count = 0;//計數器,記錄非0資料個數
        for (int i = 0; i < size; i++) {
            for (int j = 0; j < size; j++) {
                if (chessArr[i][j] != 0) {
                    count++;
                    spareseArr[count][0] = i;
                    spareseArr[count][1] = j;
                    spareseArr[count][2] = chessArr[i][j];
                }
            }
        }
        //輸出稀疏陣列的形式
        System.out.println("the sparese Array:");
        for (int i = 0; i < sum + 1; i++) {
            System.out.printf("%d %d %d\n", spareseArr[i][0], spareseArr[i][1], spareseArr[i][2]);
        }
        //稀疏陣列恢復二維陣列
        int originArr[][] = new int[spareseArr[0][0]][spareseArr[0][1]];
        //輸出恢復後的二維陣列
        for (int i = 1; i < spareseArr.length; i++) {
            originArr[spareseArr[i][0]][spareseArr[i][1]] = spareseArr[i][2];
        }
        System.out.println("the origin array:");
        for (int i = 0; i < size; i++) {
            for (int j = 0; j < size; j++) {
                System.out.print(originArr[i][j] + " ");
            }
            System.out.println();
        }    
    }
}

參考連結:尚矽谷--Java資料結構p7-p9bilibili

佇列(陣列)

佇列是一個有序列表,可以用陣列或者連結串列來實現。遵循先入先出原則,這一部分用陣列來模擬

應用場景:銀行排隊案例

佇列本身是有序列表,需要兩個變數front和rear分別標記佇列前後端,front隨著資料輸出而改變,rear隨著資料輸入而改變。還有需要一個maxSize來標記佇列的最大容量。

當存資料入列時

  • 把尾指標後移:rear+1,當front=rear [ 空 ]
  • 若尾指標rear小於佇列的最大下標maxSize-1,則將資料存入rear所指的陣列元素中,否則無法存入資料。rear == maxSize-1
    => 佇列滿

程式碼

package hello;
import java.util.Scanner;
public class Queue {
    public static void main(String[] args) {
        //建立一個佇列
        ArrayQueue queue = new ArrayQueue(3);
        char key = ' ';
        Scanner scan = new Scanner(System.in);
        boolean loop = true;
        //輸出一個選單
        while (loop) {
            System.out.println("s(show queue)");
            System.out.println("e(exit)");
            System.out.println("a(add)");
            System.out.println("g(get)");
            System.out.println("h(head)");
            key = scan.next().charAt(0);
            switch (key) {
                case 's':
                    queue.showQueue();
                    break;
                case 'a':
                    System.out.println("output a num:");
                    int value = scan.nextInt();
                    queue.addQueue(value);
                    break;
                case 'g':
                    try {
                        int res = queue.getQueue();
                        System.out.printf("get the num is: %d\n", res);
                    } catch (Exception e) {
                        //TODO: handle exception
                        System.out.println(e.getMessage());
                        break;
                    }
                    break;
                case 'h':
                    //檢視佇列頭資料
                    try {
                        int res = queue.headQueue();
                        System.out.printf("head data: %d\n", res);
                    } catch (Exception e) {
                        //TODO: handle exception
                        System.out.println(e.getMessage());
                    }
                    break;
                case 'e'://退出
                    scan.close();
                    loop = false;//退出while迴圈
                    break;
                default:
                    break;
            }
        }
    }
}
class ArrayQueue {
    private int maxSize;//陣列最大容量
    private int front;//佇列頭
    private int rear;//佇列尾
    private int[] arr;//該陣列用於存放資料,模擬佇列
    //建立佇列的構造器
    public ArrayQueue(int arrMaxSize) {
        maxSize = arrMaxSize;
        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("the queue is full~~");
            return;
        }
        //rear++;//rear後移
        //arr[rear] = n;
        arr[++rear] = n;//這是上兩行程式碼簡寫
    }
    //獲取佇列資料,出佇列
    public int getQueue() {
        //判斷是否為空
        if (isEmpty()) {
            //丟擲異常
            throw new RuntimeException("empty queue~~");
        }
        front++;
        return arr[front];
    }
    //顯示佇列所有資料
    public void showQueue() {
        if (isEmpty()) {
            System.out.println("empty queue~~");
            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("empty queue~~");
        }
        return arr[front + 1];//使front指向頭資料
    }
}

缺點:

  • 陣列只能用一次

優化:

  • 改進成為環形佇列 演算法思想:取模%

陣列模擬環形佇列

思路:

  • front變數含義做一個調整:front指向佇列第一個元素,也就是arr[front]就是佇列第一個元素
  • rear變數含義做一個調整:rear指向佇列最後一個元素的後一個位置。留出一個空間來判斷佇列是空或滿
  • 當佇列滿時,條件是:(rear+1)&maxSize == front =>佇列滿

佇列中有效資料的個數 (rear + maxSize - front) % maxSize

程式碼

import java.util.Scanner;
public class CircleArrayQueue {
    public static void main(String[] args) {
        CircleArray queue = new CircleArray(4);//佇列有效資料是3
        char key = ' ';
        Scanner scan = new Scanner(System.in);
        boolean loop = true;
        //輸出一個選單
        while (loop) {
            System.out.println("s(show queue)");
            System.out.println("e(exit)");
            System.out.println("a(add)");
            System.out.println("g(get)");
            System.out.println("h(head)");
            key = scan.next().charAt(0);
            switch (key) {
                case 's':
                    queue.showQueue();
                    break;
                case 'a':
                    System.out.println("output a num:");
                    int value = scan.nextInt();
                    queue.addQueue(value);
                    break;
                case 'g':
                    try {
                        int res = queue.getQueue();
                        System.out.printf("get the num is: %d\n", res);
                    } catch (Exception e) {
                        //TODO: handle exception
                        System.out.println(e.getMessage());
                        break;
                    }
                    break;
                case 'h':
                    //檢視佇列頭資料
                    try {
                        int res = queue.headQueue();
                        System.out.printf("head data: %d\n", res);
                    } catch (Exception e) {
                        //TODO: handle exception
                        System.out.println(e.getMessage());
                    }
                    break;
                case 'e':
                    scan.close();
                    loop = false;
                    break;
                default:
                    break;
            }
        }
    }
}

class CircleArray {
    private int maxSize;//陣列最大容量
    private int front;//佇列頭,佇列的第一個元素,不一定是0
    private int rear;//佇列尾
    private int[] arr;//該陣列用於存放資料,模擬佇列

    public CircleArray(int arrMaxSize) {
        maxSize = arrMaxSize;
        arr = new int[maxSize];
        front = 0;
        rear = 0;
    }
    public boolean isFull() {
        return (rear + 1) % maxSize == front;//+1是利用了留出的空位來判斷佇列是否為滿
    }
    public boolean isEmpty() {
        return rear == front;//初始化時rear和front都是0,如果沒有add,即可判斷為空
    }
    public void addQueue(int n) {
        if (isFull()) {
            System.out.println("full array~~");
            return;
        }
        arr[rear] = n;//直接把n賦給arr
        rear = (rear + 1) % maxSize;//考慮取模
    }
    public int getQueue() {
        if (isEmpty()) {
            throw new RuntimeException("empty array~~");
        }
        //這裡要分析出front是指向佇列的第一個元素
        //1.先把front對應的值保留到一個臨時變數
        //2.把front後移
        //3.把臨時儲存的變數返回
        int value = arr[front];    
        front = (front + 1) % maxSize;
        return value;
    }
    public void showQueue() {
        if (isEmpty()) {
            System.out.println("empty array~~");
            return;
        }
        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("empty array~~");
        }
        return arr[front];
    }
}