1 回答
TA贡献1887条经验 获得超5个赞
如果数据位于arrays中,如问题中指定的,您的代码应该是:
int[][] otherOptions = new int[neighbors.length][];
for (int nodeIdx = 0; nodeIdx < neighbors.length; nodeIdx++) {
otherOptions[nodeIdx] = new int[neighbors[nodeIdx].length - 1];
for (int i = 0, j = 0; i < neighbors[nodeIdx].length; i++) {
if (neighbors[nodeIdx][i] != preliminaryAssignments[nodeIdx]) {
otherOptions[nodeIdx][j++] = neighbors[nodeIdx][i];
}
}
}
测试
int[] preliminaryAssignments = {6, 7, 7, 7};
int[][] neighbors = {{5, 6}, {5, 7, 8, 9}, {5, 7, 9}, {5, 7, 8, 9}};
// code from above here
System.out.println(Arrays.deepToString(otherOptions));
输出
[[5], [5, 8, 9], [5, 9], [5, 8, 9]]
如果数据位于lists中,就像问题代码中使用的那样,您的代码应该是:
List<List<Integer>> otherOptions = new ArrayList<>();
for (int nodeIdx = 0; nodeIdx < neighbors.size(); nodeIdx++) {
List<Integer> others = new ArrayList<>(neighbors.get(nodeIdx));
others.remove(preliminaryAssignments.get(nodeIdx));
otherOptions.add(others);
}
测试
List<Integer> preliminaryAssignments = Arrays.asList(6, 7, 7, 7);
List<List<Integer>> neighbors = Arrays.asList(Arrays.asList(5, 6),
Arrays.asList(5, 7, 8, 9),
Arrays.asList(5, 7, 9),
Arrays.asList(5, 7, 8, 9));
// code from above here
System.out.println(otherOptions);
输出
[[5], [5, 8, 9], [5, 9], [5, 8, 9]]
如果数据位于未知类型的列表中,即get(int)可能很慢,您的代码应该是:
List<List<Integer>> otherOptions = new ArrayList<>();
Iterator<Integer> prelimIter = preliminaryAssignments.iterator();
for (Iterator<List<Integer>> neighborIter = neighbors.iterator(); neighborIter.hasNext(); ) {
List<Integer> others = new ArrayList<>(neighborIter.next());
others.remove(prelimIter.next());
otherOptions.add(others);
}
添加回答
举报