稀疏矩阵
在矩阵中,若数值为0的元素数目远远多于非0元素的数目时,则称该矩阵为稀疏矩阵。我们使用三元组来存放非零元素,row为横坐标,column为纵坐标,value为值。
本篇介绍的是稀疏矩阵的数据结构、普通转置、快速转置的方法。
三元组节点
//节点
class TripleNode {
public int row;// 行号
public int column;// 列号
public int value;// 值
public TripleNode() {
this(0, 0, 0);
}
public TripleNode(int row, int column, int value) {
this.row = row;
this.column = column;
this.value = value;
}
}
稀疏矩阵转化为三元组
基本思想是:首先计算矩阵中非零元素的个数,然后创建三元组数组,循环遍历整个矩阵,分别把非零元素的横坐标,纵坐标,值放入三元组的节点。
// 将稀疏矩阵变为三元组
public SparesMatrix(int[][] mat) {
rows = mat.length;
cols = mat[0].length;
// 计算非零元素的个数
for (int i = 0; i < rows; i++) {
for (int j = 0; j < mat[i].length; j++) {
if (mat[i][j] != 0) {
nums++;
}
}
}
int k = 0;
data = new TripleNode[nums];
for (int i = 0; i < mat.length; i++) {
for (int j = 0; j < mat[i].length; j++) {
if (mat[i][j] != 0) {
data[k] = new TripleNode(i, j, mat[i][j]);
k++;// 由于非零元素个数已知,所以不会越界
}
}
}
}
普通转置
如图,我们可以看到,转置就是横坐标与纵坐标进行互换。
普通转置的基本思想:创建一个三元组,对原三元组进行遍历,从列为0开始在原三元组中找到最小列的非零元素,存入转置三元组。
这个算法的复杂度为 O(n*t)
n为矩阵的列数,t为三元组中非零元素个数。
// 普通转置
public SparesMatrix transpose() {
SparesMatrix tmMatrix = new SparesMatrix(nums);
tmMatrix.cols = rows;
tmMatrix.rows = cols;
tmMatrix.nums = nums;
int q = 0;
// 转置并按先行后列排序
for (int col = 0; col < cols; col++) {
for (int p = 0;