我有一个 int[][] 矩阵,我想根据矩阵中的值将坐标存储在不同的数组中。 我认为我的解决方案可行,但性能不是很好...
public ArrayList<ArrayList<Coords>> storeValues(int[][] labels) {
int max = getMaxValue(labels);
ArrayList<ArrayList<Coords>> collection = new ArrayList<ArrayList<Coords>>();
ArrayList<Coords> coords;
while (max > 0) {
coords = new ArrayList<Coords>();
for (int x = 0; x < labels.length; x++) {
for (int y = 0; y < labels[0].length; y++) {
if (max == labels[x][y]) {
coords.add(new Coords(x,y));
}
}
}
collection.add(coords);
--max;
}
return collection;
}
private int getMaxValue(int[][] labels) {
int max = labels[0][0];
for (int tabValue[] : labels) {
for (int value : tabValue) {
if (max < value) {
max = value;
}
}
}
return max;
}
例如:
我的矩阵包含
[ [ 0, 0, 0 ],
[ 1, 1, 1 ],
[ 1, 2, 2 ],
[ 2, 2, 5 ] ]
预期结果
ArrayList{
ArrayList{ Coord[0,0], Coord[1,0], Coord[2,0] }, // list of 0 value
ArrayList{ Coord[0,1], Coord[1,1], Coord[2,1], Coord[0,3] }, // list of 1 value
...
}
最佳答案
您的目标应该是尽可能少地进行迭代。如果您使用 Map 构建所需的数据结构,则实际上可以在一次(嵌套)迭代中完成。这里最有帮助的是 TreeMap
,因为它会自动按键排序..
逻辑是构建一个 new TreeMap<Integer, ArrayList<Coords>>
,而不是嵌套列表。 .
Integer-key 是您的值,arrayList 是该值的坐标列表。
您像以前一样遍历矩阵,但不计算 max
.这为您节省了整个getMaxValue
方法和外部 while 循环。
对于每个值,您首先检查是否 TreeMap
有一个带有那个键的条目。如果是,请添加新的 Coord
到 map.get(val)。如果不是,创建一个 new ArrayList<Coord>
, 添加您的 Coord
到该列表,并将其放入 map 中。
如果您绝对必须将 ArrayList> 作为返回类型,您可以在末尾使用 return new ArrayList<ArrayList<Coord>>(map.values())
简单地转换 map 的 valueSet。
关于Java更好的方法来通过特定值存储int矩阵中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23172602/