gpt4 book ai didi

java - Java 中的稀疏矩阵

转载 作者:太空宇宙 更新时间:2023-11-04 10:39:54 24 4
gpt4 key购买 nike

稀疏矩阵是元素主要为零的矩阵。下面的代码使用 LinkedList 的 ArrayList 来实现稀疏矩阵。它定义了一个 Element 类来存储元素的列号和值。每行都由仅具有非零值的元素的 LinkedList 表示。几乎没有行(如果有的话)全为零,因此 ArrayList 用于按行升序存储每一行​​的 LinkedList。

class Element { 
public int column;
public int value; }

public class SparseMatrix {
private int mRows; // Number of rows
private int mCols; // Number of columns
private ArrayList<LinkedList<Element>> mMatrix;

1) 如何使用带有参数 (int r, int c) 的 getter,它表示特定的行号和列号来检索矩阵的该行和列中的值?

2) 如何使用带有参数(int r、int c、int v)的 setter 将 r 行和 c 列的值设置为 v? (注意:如果节点尚不存在,则必须创建一个新节点。如果 v 为零,则删除该节点。)

如果我错了,请纠正我,但要分别获取矩阵的行数和列数,我会这样做:

get(int r, int c) {
int rowSize = mMatrix.length;
int colSize = mMatrix[0].length;
}

但是,我不确定随后如何使用它。

最佳答案

我将把代码和一些基本注释放在此处。您应该能够根据您的需要进行调整。我不会使用 class Element 因为它持有一个 int。值的意义是无关紧要的。

private static int mRows; // Number of rows 
private static int mCols; // Number of columns
private static final ArrayList<LinkedList<Integer>> mMatrix = new ArrayList<>();


public static void main(String[] args) {
mRows = 7; //example
mCols = 4; //example

//init your matrix
for (int i = 0; i < mRows; i++) { //add new row 7 times
mMatrix.add(new LinkedList<>());
for (int j = 0; j < mCols; j++) {
mMatrix.get(i).add(0); // add Integer with value 0 (4 times)
}
}

//test
setValue(5, 3, 159);
System.out.println(getValue(5, 3));

}

public static void setValue(int r, int c, Integer v) {
//before call be sure that r < mRows and c < mCols
mMatrix.get(r).set(c, v); //replaces existing Integer
}

public static Integer getValue(int r, int c) {
//before call be sure that r < mRows and c < mCols
return mMatrix.get(r).get(c);
}

关于java - Java 中的稀疏矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49105099/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com