Java更好的方法来通过特定值存储int矩阵中的值

标签 java matrix

我有一个 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/

相关文章:

matlab - 如何更改矩阵中多个点的值?

opengl - 在 OpenGL 中存储和加载矩阵

matlab - 在 Matlab 中绘制 A^x * v 中向量的第一个元素(矩阵幂)

java - 加速 Java

java - JBox2D - 查找碰撞坐标

java - 使用 Java URLConnection 关闭 Cookie

matlab - 如何有条件地获取矩阵行?

python - Python 中的希尔伯特矩阵

java - 从sup标签中检索文本

java - Android Canvas 图形