1. 程式人生 > 實用技巧 >JAVA資料結構與演算法(一)

JAVA資料結構與演算法(一)

目錄

    1. 經典考題:

      1. 字串匹配問題

        1)有一個字串 str1="abdbciauociebufebcdlkjsncklds",和一個子字串 str2="fe";

        2)現在要判斷str1是否含有str2,如果存在,返回第一次出現的位置,如果沒有,則返回-1。

        3)要求用最快的速度完成匹配

        該資料用於存放資料,模擬佇列

        · 暴力匹配 [簡單,但是效率低]
        · KMP演算法《部分匹配表》

      2. 漢諾塔

      3. 八皇后問題(分治演算法)

    • 資料結構

      包括線性結構和非線性結構

      1)線性結構特點是資料元素之間存在一對一的線性關係。

      2)線性結構有兩種不同的儲存結構,即順序儲存結構(陣列,儲存元素連續)和鏈式儲存結構(連結串列,元素不一定連續)。順序儲存的線性表稱為順序表。

      3)線性結構常見有:陣列,佇列,連結串列和棧。

      非線性結構包括:二維陣列、多維陣列,廣義表,樹結構,圖結構

    1. 演算法的複雜度分析

      1. 時間複雜度分析
    • 程式碼實現

      1)佇列操作

      1. package queue;
        
        import java.util.Scanner;
        
        public class QueueOp {
        
            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("l(location):顯示佇列指定位置資料");
                    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.outQueue();
                                System.out.printf("取出的資料是%d\n", res);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            break;
                        case 'l':
                            int appoint = scanner.nextInt();
                            queue.ShowAppoint(appoint);
                    }
                }
        
        
            }
        
        }
        
        // 初始化
        class ArrayQueue {
            /**
             * 變數宣告:
             * 1 陣列最大容量
             * 2 佇列頭
             * 3 佇列尾
             * 4 佇列陣列(一維)
             */
            private int MaxSize;
            private int front;
            private int rear;
            private int[] queue;
        
            public ArrayQueue(int MaxSize) {
                // 對宣告的變數進行初始化
                this.MaxSize = MaxSize;
                front = -1;
                rear = -1;
                queue = new int[MaxSize];
            }
        
            // 判斷佇列是否滿
            public boolean isFull() {
                return rear == MaxSize;
            }
        
            // 判斷佇列是否為空
            public boolean isEmpty() {
                return front == rear;
            }
        
            // 加資料
            public void addQueue(int n) {
                if (isFull()) {
                    System.out.println("佇列滿,不能加入資料~");
                    return;
                }
                rear++; //讓rear後移
                queue[rear] = n;
        
            }
        
            // 取資料
            public int outQueue() {
                if (isEmpty()) {
                    throw new RuntimeException("佇列空,不能取資料~");
                }
                front++; //讓front後移
                return queue[front];
            }
        
            // 顯示佇列所有資料
            public void ShowQueue() {
                if (isEmpty()) {
                    throw new RuntimeException("佇列空,無資料~");
                }
                int t = -1;
                t++; //讓front後移
                System.out.printf("queue [%d]=%d/t", t, queue[t]);
            }
        
            //顯示佇列指定位置資料
            public void ShowAppoint(int appoint) {
                if (appoint <= -1 || appoint >= MaxSize) {
                    throw new RuntimeException("佇列空,無資料~");
                }
                int t = -1;
                t++; //讓front後移
                System.out.printf("queue [%d]=%d\n", t, queue[t]);
            }
        }
        

      2)環形佇列

      關鍵點:

        1)int[] arr 是定義一個整型陣列當佇列

        2)maxSize是陣列的最大容量

        (這裡規定,滿佇列時元素的個數是maxSize-1)

        3)front指向佇列的第一個元素,也就是說 array[front] 是佇列的第一個元素

        4)rear指向佇列的最後一個元素,初值為0

        5)佇列滿的條件:(rear + 1) % maxSize == front

        佇列為空的條件: rear == front

      package queue;
      
      import java.util.Scanner;
      
      public class CircleQueue {
          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];
          }
      }