数据结构与算法
1、数据结构与算法概述
1.1 概述
数据结构(data structure)是一门研究组织数据方式的学科,有了编程语言也就有了数据结构.学好数据结构可以编写出更加漂亮,更加有效率的代码。
程序 = 数据结构 + 算法
数据结构是算法的基础,想要学好算法,需要把数据结构学到位。
1.2 分类
数据结构包括:线性结构和非线性结构
- 线性结构
- 数据元素之间存在一对一的线性关系
- 有两种不同的存储结构:顺序存储结构和链式存储结构。
-
- 顺序存储的线性表称为顺序表,顺序表中的存储元素是连续的
- 链式存储的线性表称为链表,链表中的存储元素不一定是连续的,元素节点中存放数据元素以及相邻元素的地址信息
- 常见的线性结构有:数组、队列、链表和栈
- 非线性结构
- 典型的非线性结构包括:多维数组,树结构,图结构
2、稀疏数组与队列
2.1 稀疏数组
2.1.1 概念
稀疏数组(sparse array):当一个数组中的大多数元素值是一样,仅有少数的值不同时,在对数组进行保存的时候,全量的保存可能会占用很大的空间,且过多重复的数字是没有意义的,因此会采用稀疏数组对数据进行保存。
2.1.2 应用场景
在实际中,对于一个棋类游戏中,棋盘模拟经常采用一个二维数组来表示,数组中用0值来代表棋盘,1代表黑子的位置,2代表白子的位置,在对棋盘做存盘退出和续接上盘的功能时,需要对棋盘数据进行保存。
如上图所示,在进行存盘的时候,二维数组表示的棋盘很多值是默认值0, 以此方式进行存盘,会记录很多没有意义的数据。
2.1.3 稀疏数组解决
在上述问题中,当数组中大部分元素为0,或者为同一个值的数组,而只有少数值不同时,可以使用稀疏数组来保存该数组。
稀疏数组的处理方法是:
1)记录数组一共有几行几列,有多少个不同的值
2)把具有不同值的元素的行列及值记录在一个小规模的数组中,从而缩小程序的规模
普通二维数组转稀疏数组的过程:
-
稀疏数组中行数row: 二维数组中不同值的个数+1;
-
稀疏数组中列数column:3列
数组中元素表示:
-
第一行数据:二维数组的行数,二维数组的列数, 二维数组中不同值的个数
-
第二行数据:不同值所在的行,不同值所在的列,不同值的数值
-
…
针对上述二维数组的转换,如下所示:
2.1.4 代码实现
package com.kevin.sparsearray;
/**
* @author : kevin ding
* @date : 2022/2/9 13:42
* @description : 矩阵和稀疏矩阵的转换 棋盘的二维数据矩阵存储-->先将普通的二维数组转换成为一个稀疏数组
* 在棋盘中0代表棋格,1代表黑子,2代表白子====>二维数组中会出现很多0,存储时没有意义,采用稀疏数组
* 稀疏数组:数组一共有三列,第一行的三列分别记录原数组有几行几列,非零个数几个
* 截下来的行数分别记录非零元素的位置和值
*/
public class SparseArray {
public static void main(String[] args) {
// 1.首先创建一个原二维数组
int[][] array = new int[10][10];
array[2][3] = 1;
array[3][4] = 2;
array[3][3] = 1;
array[1][3] = 2;
SparseArray demo = new SparseArray();
// 2. 打印出原数组:
System.out.println("原数组为:");
demo.printArray(array);
// 3. 将array转成稀疏数组
int[][] sparseArray = demo.arrayTransToSparse(array);
// 4. 打印稀疏数组
System.out.println("转成稀疏数组之后:");
demo.printArray(sparseArray);
// 5. 将稀疏矩阵还原
int[][] normalArray = demo.sparseTransToNormalArray(sparseArray);
// 6. 将还原后的矩阵输出
demo.printArray(normalArray);
}
/**
* 原数组转稀疏数组的过程:
* 1.遍历整个原数组,记录所有不为零的元素个数
* 2.根据不为零的元素个数,创建一个稀疏数组:sparseArray arr= new int[sum+1] [3];
* 3.分别将不为零的元素的位置存放到对应稀疏数组中
*/
public int[][] arrayTransToSparse(int[][] array){
// 1. 遍历整个原始数组,记录不为零的元素个数
int count = 0;
for(int[] rows : array){
for(int data : rows){
if(data != 0){
count++ ;
}
}
}
// 2. 得到不为零的元素个数,创建一个稀疏数组:
int[][] sparseArray = new int[count+1][3];
sparseArray[0][0] = array.length;
sparseArray[0][1] = array[0].length;
sparseArray[0][2] = count;
// 3. 将不为零的元素存放到对应的位置
int tempCount = 0; // 记录当前是第几个不为0的元素
for(int i = 0; i < array.length; i++){
for(int j = 0; j < array[i].length; j++){
if(array[i][j] != 0){
tempCount ++;
sparseArray[tempCount][0] = i;
sparseArray[tempCount][1] = j;
sparseArray[tempCount][2] = array[i][j];
}
}
}
return sparseArray;
}
// 遍历数组
public void printArray(int[][] arr){
for(int[] rows: arr){
for (int data: rows){
System.out.print(data + "\t" );
}
System.out.println();
}
}
/**
* 稀疏数组转换成原数组:
* 1. 根据稀疏数组的第一行第一列、第一行第二列的值来创建原数组
* 2. 将其余行列中非零的数进行填充
*/
public int[][] sparseTransToNormalArray(int[][] array){
// 首先判断稀疏矩阵是否有值
if(array == null){
throw new RuntimeException("稀疏数组为空");
}
int[][] normalArray = new int[array[0][0]][array[0][1]];
// 从第二行开始,遍历稀疏数组的每一行
for(int i= 1; i<array.length; i++){
int rowIndex = array[i][0];
int columnIndex = array[i][1];
normalArray[rowIndex][columnIndex] = array[i][2];
}
return normalArray;
}
}
2.2 队列
2.2.1 介绍
- 队列是一个有序列表,可以用数组或是链表来实现;
- 队列遵循**先进先出 (FIFO)**的原则。即:先存入队列的数据,要先取出,后存入的要后取出;
- 队列示意图如下:
2.2.2 数组模拟队列
- 初始化:
- 使用数组的结构来模拟队列,应声明
maxSize
为是该队列的最大容量,rear
指向队尾,front
指向队首,int[] array = new int[maxSize]
声明数组模拟的队列; 初始化队尾和队首都指向-1;
- 模拟队列的方法
-
判空:队列是否为空:rear == front
-
队满:队列是否已满:rear == maxSize-1;
-
入队(添加数据):
addQueue
:- 先判断队列是否已满,若满无法添加数据。
- 队列未满,rear+=1;array[rear] = value;
-
出队(取出数据):
getQueue
- 先判断队列是否为空,若已空,没有元素出队;
- 队列有值,front+=1; return array[front];
-
遍历(显示所有数据):
- 先判断队列是否为空
- 从队列的front位置开始显示,一直到rear即可,遍历
2.2.3 代码实现
- 数组模拟队列
package com.kevin.arrayqueue;
/**
* @author : kevin ding
* @date : 2022/2/9 11:29
* @description : 创建一个队列的类queue
* 对列是一个有序的列表,可以用数组或链表来实现;对列遵循先进先出的原则:先存入对列的数据,先被取出来
*/
public class Queue {
// 对列的类需要有属性最大容量,队头、队尾
private int maxSize;
private int front;
private int rear;
// 数组模拟对列
private int[] arr;
// 队列的构造方法
public Queue( int maxSize){
this.maxSize = maxSize;
this.arr = new int[this.maxSize];
// 队头和队尾的初始 均指向-1
this.front = -1;
this.rear = -1;
}
public boolean isFull(){
// 当队尾指向最后一个index时,队列满
return this.rear == this.maxSize - 1;
}
public boolean isEmpty(){
// 当队头和队尾值相等时,队列为空
return this.rear == this.front;
}
public void addDataToQueue(int num){
// 添加元素 首先判断队列是否满了
if(isFull()){
System.out.println("队列已经满了,不能添加...");
return;
}
// 没有满的情况下,直接将队尾指向+1
this.rear += 1;
arr[this.rear] = num;
}
public int getDataFromQueue(){
// 首先判断队列是否为空
if(isEmpty()){
throw new RuntimeException("队列为空,无法取值");
}
//队首+1 再取值
this.front += 1;
return arr[this.front];
}
public void showQueue(){
// 判空
if(isEmpty()){
System.out.println("队列为空,显示个毛线..");
return;
}
// 需要从队列的front开始显示 显示到队尾
for(int index = front+1; index <= rear; index++){
System.out.print(this.arr[index] + "\t");
}
System.out.println();
}
public int showFront(){
// 显示队头元素之前先判空
if(isEmpty()){
throw new RuntimeException("队列为空,没有队首");
}
return arr[this.front+1];
}
}
- 控制台验证
package com.kevin.arrayqueue;
import java.util.Scanner;
/**
* @author : kevin ding
* @date : 2022/2/9 11:26
* @description : 使用数组实现队列验证
*/
public class ArrayQueueDemo {
public static void main(String[] args) {
// 1.通过Queue类创建一个队列
Queue queue = new Queue(4);
// 2. 写一个界面完成对队列功能的验证
boolean loop = true;
char choose = ' ';
Scanner sc = new Scanner(System.in);
while(loop){
System.out.println("a(add): 添加数据到队列");
System.out.println("g(get): 从队列中获取数据");
System.out.println("h(head):显示队首元素");
System.out.println("s(show):显示队列所有元素");
System.out.println("e(exit): 退出");
System.out.println("请输入您需要完成的功能:");
// 接收控制台的一个输入
choose = sc.next().charAt(0);
// 判断choose操作
switch (choose){
case 'a':
System.out.println("请输入要插入的数据:");
int num = sc.nextInt();
queue.addDataToQueue(num);
System.out.println();
break;
case 'g':
try{
int data = queue.getDataFromQueue();
System.out.println("取出的数据为:" + data);
}catch (Exception ex){
System.out.println(ex.getMessage());
}
System.out.println();
break;
case 'h':
try {
int frontData = queue.showFront();
System.out.println("队列的头是:" + frontData);
}catch (Exception ex){
ex.printStackTrace();
}
System.out.println();
break;
case 's':
queue.showQueue();
System.out.println();
break;
case 'e':
loop = false;
System.out.println();
break;
default:
break;
}
}
sc.close();
System.out.println("程序退出....");
}
}
2.3 环形队列
上述代码的验证中,发现数组模拟的队列只能使用一次,一旦添加数据的个数达到maxSize
,即使将数据全部出队,也无法再进行添加元素。即为一次性使用的队列,下面采用数组模拟环形队列,每当队列中有元素出队,就可以将新的元素入栈,提高重用性。
2.3.1 思路分析:
- 对于环形队列,采用取模的方式来实现
- front的变量含义:front指向队列的第一个元素,即初始化为0,array[front]即为队首元素;
- rear的变量含义:rear指向队列最后一个元素的后一个位置,即将array空出一个空间作为约定。rear的初始值也为0;
- 队列满的条件:
(rear+1) % maxSize == front
; - 队列空的条件:
rear == front
; - 有效数据的个数:
(rear + maxSize - front) % maxSize
2.3.2 代码实现
- 循环队列代码
package com.kevin.circlequeueDemo;
/**
* @author : kevin ding
* @date : 2022/2/10 0:12
* @description : 创建一个循环队列的类
*/
public class CircleQueue {
// 对列的类需要有属性最大容量,队头、队尾
private int maxSize;
private int front;
private int rear;
// 数组模拟对列
private int[] arr;
// 队列的构造方法
public CircleQueue( int maxSize){
this.maxSize = maxSize;
this.arr = new int[this.maxSize];
// 队头指向 0 直接表示当前队首元素
this.front = 0;
// 队尾初始也为0,队尾指向最后一个元素的后一位,其中约定数组预留一个空的位置不存储数据,做一个约定
this.rear = 0;
}
public boolean isFull(){
// 当进行预留一个空位做约定时,判断是否满的情况发生变化:(rear + 1) % maxSize == front 表示满
return (this.rear + 1) % this.maxSize == front;
}
public boolean isEmpty(){
// 当队头和队尾值相等时,队列为空 为空的判断没有发生变化
return this.rear == this.front;
}
public void addDataToQueue(int num){
// 添加元素 首先判断队列是否满了
if(isFull()){
System.out.println("队列已经满了,不能添加...");
return;
}
// 没有满的情况下,直接向队尾添加一个元素,添加完之后,队尾后移一位(可能会越界,需要取模)
arr[this.rear] = num;
this.rear = (this.rear + 1) % this.maxSize;
}
public int getDataFromQueue(){
// 首先判断队列是否为空
if(isEmpty()){
throw new RuntimeException("队列为空,无法取值");
}
//因为需要将值返回,所以需要定义一个变量来存储值,取出队首的值之后,需要先将front后移一位,才能返回值
// 后移时,也需要考虑数组越界的问题,取模
int currentVal = arr[this.front];
this.front = (this.front + 1) % this.maxSize;
return currentVal;
}
public int totalNum(){
// 队列中元素的总个数为:(rear + maxSize - front) % maxSize
return (this.rear + this.maxSize - this.front) % this.maxSize;
}
public void showQueue(){
// 判空
if(isEmpty()){
System.out.println("队列为空,显示个毛线..");
return;
}
// 需要从队列的front开始显示 遍历多少个为止(index < front + total)(队列中总的元素个数)
for(int index = front; index < front + totalNum(); index++){
System.out.print("arr[" + (index % this.maxSize) + "]=" + this.arr[index % this.maxSize] + "\t");
}
System.out.println();
}
public int showFront(){
// 显示队头元素之前先判空
if(isEmpty()){
throw new RuntimeException("队列为空,没有队首");
}
//直接front即为队首
return arr[this.front];
}
}
- 控制台测试
package com.kevin.circlequeueDemo;
import java.util.Scanner;
/**
* @author : kevin ding
* @date : 2022/2/10 0:27
* @description :
*/
public class CircleQueueTest {
public static void main(String[] args) {
System.out.println("通过数组模拟循环队列...");
// 1.通过Queue类创建一个队列
CircleQueue queue = new CircleQueue(4);
// 2. 写一个界面完成对队列功能的验证
boolean loop = true;
char choose = ' ';
Scanner sc = new Scanner(System.in);
while(loop){
System.out.println("a(add): 添加数据到队列");
System.out.println("g(get): 从队列中获取数据");
System.out.println("h(head):显示队首元素");
System.out.println("s(show):显示队列所有元素");
System.out.println("e(exit): 退出");
System.out.println("请输入您需要完成的功能:");
// 接收控制台的一个输入
choose = sc.next().charAt(0);
// 判断choose操作
switch (choose){
case 'a':
System.out.println("请输入要插入的数据:");
int num = sc.nextInt();
queue.addDataToQueue(num);
System.out.println();
break;
case 'g':
try{
int data = queue.getDataFromQueue();
System.out.println("取出的数据为:" + data);
}catch (Exception ex){
System.out.println(ex.getMessage());
}
System.out.println();
break;
case 'h':
try {
int frontData = queue.showFront();
System.out.println("队列的头是:" + frontData);
}catch (Exception ex){
ex.printStackTrace();
}
System.out.println();
break;
case 's':
queue.showQueue();
System.out.println();
break;
case 'e':
loop = false;
System.out.println();
break;
default:
break;
}
}
sc.close();
System.out.println("程序退出....");
}
}