小白最近在学习数据结构这里给大家分享下
首先:咱们得明白啥是稀疏数组
1、稀疏数组一般是n行3列
2、第一行的第一列是二维数组的总行数
3、第一行的第二列是二维数组的总列数
4、第一行的第三列是二维数组的有效数据数
5、其他行的第一列是二维数组有效数据的行
6、其他行的第二列是二维数组有效数据的列
7、其他行的第三列是二维数组有效数据
列子:
二维数组:
0 0 0 0
0 2 0 1
0 0 0 0
0 0 0 0
稀疏数组:
4 4 2
1 1 2
1 3 1
注意:
4 4 2表示总行数,总列数,有效数据
1 1 2表示二维数组的第二行,第二列,值为2
三者转换代码:
1、 // 稀疏数组与二维数组互转
public void sparseArrays() throws IOException {
// 创建二维数组
System.out.println("二维数组");
int [][] array = new int[11][11];
array[1][2] = 1;
array[2][3] = 2;
array[4][5] = 2;
array[9][8] = 1;
array[7][4] = 2;
array[3][2] = 1;
for(int [] row : array) {
for(int item : row) {
System.out.printf("%d\t", item);
}
System.out.println();
}
System.out.println("二维数组转稀疏数组");
// 二维数组转稀疏数组
// 获取二维数组的行数 array.length
// 获取二维数组的列数 array[0].length
int sum = 0; // 有效数据
for(int i=0; i<array.length; i++){
for (int j=0; j<array.length; j++){
if(array[i][j] != 0){
sum++;
}
}
}
int[][] sparseArray = new int[sum+1][3];
sparseArray[0][0] = array.length;
sparseArray[0][1] = array[0].length;
sparseArray[0][2] = sum;
int count = 0;
for(int i=0; i<array.length; i++){
for (int j=0; j<array.length; j++){
if(array[i][j] != 0){
count++;
sparseArray[count][0] = i;
sparseArray[count][1] = j;
sparseArray[count][2] = array[i][j];
}
}
}
for(int [] row : sparseArray){
for (int item : row){
System.out.printf("%d\t", item);
}
System.out.println();
}
File file = sparseFile(sparseArray);
int[][] sparseArray1 = fileSparse(file);
System.out.println("从文件中获取稀疏数组");
for(int [] row : sparseArray1){
for (int item : row){
System.out.printf("%d\t", item);
}
System.out.println();
}
System.out.println("稀疏数组转二维数组");
int array1[][] = new int[sparseArray1[0][0]][sparseArray1[0][1]];
for (int i=1; i<sparseArray1.length; i++){
array1[sparseArray1[i][0]][sparseArray1[i][1]] = sparseArray1[i][2];
}
for (int [] row : array1){
for (int item : row ){
System.out.printf("%d\t", item);
}
System.out.println();
}
}
2、// 稀疏数组转为文件
public File sparseFile(int [][] sparse) throws IOException {
File file = new File("F:\\sparse.txx");
FileWriter out = new FileWriter(file);
for (int [] row : sparse){
for (int item : row){
out.write(item + "\t");
}
out.write("\r\n");
}
out.close();
return file;
}
3、// 将文件转为稀疏数组
public int[][] fileSparse(File file) throws IOException {
FileReader fileReader = new FileReader(file);
BufferedReader in = new BufferedReader(fileReader);
String line;
int row = 1;
line = in.readLine();
String[] len = line.split("\t");
int [][] sparse = new int[Integer.parseInt(len[2])+1][3];
sparse[0][0] = Integer.parseInt(len[0]);
sparse[0][1] = Integer.parseInt(len[1]);
sparse[0][2] = Integer.parseInt(len[2]);
while ((line = in.readLine()) != null){
String[] temp = line.split("\t");
for (int i=0; i<temp.length; i++){
sparse[row][i] = Integer.parseInt(temp[i]);
}
row++;
}
in.close();
return sparse;
}
这是小白学习时写的代码,分享给大家希望有帮助