我需要在要使用 List<List<Integer>>
插入的排序矩阵中进行搜索到达
我能够找到解决方案,但不使用 List<List>>
.
这是我尝试过但没有成功
public class SearchMat {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
List<Integer> arrList = new ArrayList<Integer>();
while (scanner.hasNextIint()) {
arrList.add(scanner.nextInt());
}
List<List<Integer>> array = new ArrayList<List<Integer>>();
for(List<Integer> list : arrList){
array.addAll(list);
}
}
}
最佳答案
想象一下以下输入:10 20 15 25
您当前的代码将创建一个 1x4 矩阵,例如:
+-----------------+ +-----------------+ +-------------+
| List (size 1) | ---> | List (size 4) | ---> | 10 20 15 25 |
+-----------------+ +-----------------+ +-------------+
你想要的应该是这样的:
+-----------------+ +-----------------+ +-------+
| List (size 2) | -+-> | List (size 2) | ---> | 10 20 |
+-----------------+ | +-----------------+ +-------+
| +-----------------+ +-------+
+-> | List (size 2 | ---> | 15 25 |
+-----------------+ +-------+
您也没有任何方式对输入进行排序,也不知道矩阵应该有多长。
如果您假设输入已排序并且您的行应该只有 4 列,这将创建您想要的 2D 矩阵 Nx4 表示形式:
List<List<Integer>> matrix = new ArrayList<List<Integer>>();
while (scanner.hasNextIint()) {
List<Integer> list = new ArrayList<Integer>();
for(int i=0; i<4; i++){
list.add(scanner.nextInt());
}
matrix.add(list);
}
希望这能引导您走向正确的方向。
关于java - 在 Java 中搜索排序矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59229556/