數據結構-稀疏數組和隊列

一、稀疏 sparsearray 數組

1、先看一個實際的需求

  • 編寫的五子棋程序中,有存盤退出和續上盤的功能。
    在這裏插入圖片描述
  • 分析問題:
    因爲該二維數組的很多值是默認值 0, 因此記錄了很多沒有意義的數據.->稀疏數組。

2、基本介紹

當一個數組中大部分元素爲0,或者爲同一個值的數組時,可以使用稀疏數組來保存該數組。
稀疏數組的處理方法是:

  1. 記錄數組一共有幾行幾列,有多少個不同的值
  2. 把具有不同值的元素的行列及值記錄在一個小規模的數組中,從而縮小程序的規模
  • 稀疏數組舉例說明
    在這裏插入圖片描述

3、應用實例

  1. 使用稀疏數組,來保留類似前面的二維數組(棋盤、地圖等等)
  2. 把稀疏數組存盤,並且可以從新恢復原來的二維數組數
  3. 整體思路分析
    在這裏插入圖片描述

4、代碼實現

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[4][5] = 2;

        // 輸出原始的二維數組 System.out.println("原始的二維數組~~");
        for (int[] row : chessArr1) {
            for (int data : row) {
                System.out.printf("%d\t", data);
            }
            System.out.println();
        }
        // 將二維數組 轉 稀疏數組的思
        // 1. 先遍歷二維數組 得到非 0 數據的個數
        int sum = 0;
        for (int i = 0; i < 11; i++) {
            for (int j = 0; j < 11; j++) {
                if (chessArr1[i][j] != 0) {
                    sum++;
                }
            }
        }
        // 2. 創建對應的稀疏數組
        int sparseArr[][] = new int[sum + 1][3];
        // 給稀疏數組賦值
        sparseArr[0][0] = 11;
        sparseArr[0][1] = 11;
        sparseArr[0][2] = sum;

        // 遍歷二維數組,將非 0 的值存放到 sparseArr 中
        int count = 0; //count 用於記錄是第幾個非 0 數據
        for (int i = 0; i < 11; i++) {
            for (int j = 0; j < 11; j++) {
                if (chessArr1[i][j] != 0) {
                    count++;
                    sparseArr[count][0] = i;
                    sparseArr[count][1] = j;
                    sparseArr[count][2] = chessArr1[i][j];
                }
            }
        }
        // 輸出稀疏數組的形式
        System.out.println();
        System.out.println("得到稀疏數組爲~~~~");
        for (int i = 0; i < sparseArr.length; i++) {
            System.out.printf("%d\t%d\t%d\t\n", sparseArr[i][0], sparseArr[i][1], sparseArr[i][2]);
        }
        System.out.println();
        //將稀疏數組 --》 恢復成 原始的二維數組
        /*
        *  */
        /**
         * 1. 先讀取稀疏數組的第一行,根據第一行的數據,創建原始的二維數組,比如上面的 chessArr2 = int[11][11]
         *         2. 在讀取稀疏數組後幾行的數據,並賦給 原始的二維數組 即可.
         */
        //1. 先讀取稀疏數組的第一行,根據第一行的數據,創建原始的二維數組
        int chessArr2[][] = new int[sparseArr[0][0]][sparseArr[0][1]];
        //2. 在讀取稀疏數組後幾行的數據(從第二行開始),並賦給 原始的二維數組 即可
        for (int i = 1; i < sparseArr.length; i++) {
            chessArr2[sparseArr[i][0]][sparseArr[i][1]] = sparseArr[i][2];
        }
        // 輸出恢復後的二維數組 System.out.println(); System.out.println("恢復後的二維數組");
        for (int[] row : chessArr2) {
            for (int data : row) {
                System.out.printf("%d\t", data);
            }
            System.out.println();
        }
    }
}
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374

二、隊列

1、 隊列的一個使用場景

  • 銀行排隊的案例:
    在這裏插入圖片描述
  • 隊列介紹
  1. 隊列是一個有序列表,可以用數組或是鏈表來實現。
  2. 遵循先入先出的原則。即:先存入隊列的數據,要先取出。後存入的要後取出
  3. 示意圖:(使用數組模擬隊列示意圖)
    在這裏插入圖片描述
  • 數組模擬隊列思路
     隊列本身是有序列表,若使用數組的結構來存儲隊列的數據,則隊列數組的聲明如下圖, 其中 maxSize 是該隊 列的最大容量。
     因爲隊列的輸出、輸入是分別從前後端來處理,因此需要兩個變量 front 及 rear 分別記錄隊列前後端的下標, front 會隨着數據輸出而改變,而 rear 則是隨着數據輸入而改變,如圖所示:
    在這裏插入圖片描述
    當我們將數據存入隊列時稱爲”addQueue”,addQueue 的處理需要有兩個步驟:思路分析
  1. 將尾指針往後移:rear+1 , 當 front == rear 【空】
  2. 若尾指針 rear 小於隊列的最大下標 maxSize-1,則將數據存入 rear 所指的數組元素中,否則無法存入數據。

3.2.3 數組模擬隊列思路
rear == maxSize - 1[隊列滿]

2、代碼實現

package com.hellobike.finance;

import java.util.Scanner;

public class ArrayQueueDemo {
    public static void main(String[] args) { //測試一把
        //創建一個隊列
        ArrayQueue queue = 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':
                    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("程序退出~~");
        }
    }

    // 使用數組模擬隊列-編寫一個 ArrayQueue 類
    static 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; // 指向隊列頭部,分析出 front 是指向隊列頭的前一個位置.
            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++; // 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];
        }
    }
}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124

三、 數組模擬環形隊列

分析說明:

  1. 尾索引的下一個爲頭索引時表示隊列滿,即將隊列容量空出一個作爲約定,這個在做判斷隊列滿的
    時候需要注意 (rear + 1) % maxSize == front 滿]
  2. rear == front [空]
  3. 分析示意圖:
    在這裏插入圖片描述

代碼實現:

import java.util.Scanner;

public class CircleArrayQueueDemo {
    public static void main(String[] args) { //測試一把
        System.out.println("測試數組模擬環形隊列的案例~~~");
        // 創建一個環形隊列
        CircleArray queue = 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':
                    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("程序退出~~");
    }
}

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 = (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 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() {
        // rear = 2
        // front = 1
        // maxSize = 3
        return (rear + maxSize - front) % maxSize;
    }

    // 顯示隊列的頭數據, 注意不是取出數據
    public int headQueue() {
        // 判斷
        if (isEmpty()) {
            throw new RuntimeException("隊列空的,沒有數據~~");
        }
        return arr[front];
    }
}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142

來自尚硅谷韓順平老師筆記

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章