首页 > 解决方案 > 3 维数组的哪些索引具有最大值?

问题描述

我有一个整数的三维数组,每个维度代表一种颜色 R、G 或 B,整数代表 R、G、B 的颜色值在图像中出现的次数。

现在我需要找到这张图片中出现次数最多的 X 颜色。

到目前为止,我已经创建了一个结构列表,该结构同时包含颜色和计数。我遍历原始数组的三个维度,对于每个大于列表中第一项的值,我替换列表中的项,然后对列表进行排序。

这当然需要很多时间,每次运行将近 2 秒。

如何以省时的方式找到此数组中出现最多的 X 颜色?目前在我的计算机上每次运行要花费我 2 秒,但这段代码需要在 Raspberry Pi 上运行,这需要更长的时间。理想情况下,我在 Pi 上寻找 100 毫秒的时间,但我不知道如何到达那里或使用什么算法。

编辑:根据 Jerry 的要求添加了代码

// Struct holding colours & colour count
struct ColourCount
{
    public byte red;
    public byte green;
    public byte blue;
    public Int32 count;
}

List<Int32> matrix = new List<Int32>();
ColourCount[] count = new ColourCount[100];
int idx = 0;
for (int r = 0; r < 256; r++)
{
    for (int g = 0; g < 256; g++)
    {
        for (int b = 0; b < 256; b++)
        {
            if (idx < count.Length)
            {
                count[idx].red = (byte)r;
                count[idx].green = (byte)g;
                count[idx].blue = (byte)b;
                count[idx].count = colours[r, g, b];
                idx++;
            }
            else
            {
                Array.Sort<ColourCount>(count, (x, y) => (x.count.CompareTo(y.count)));
                if (colours[r, g, b] > count[0].count)
                {
                    count[0].red = (byte)r;
                    count[0].green = (byte)g;
                    count[0].blue = (byte)b;
                    count[0].count = colours[r, g, b];
                }
            }
        }
    }
}

for (int i = 0; i < count.Length; i++)
{
    matrix.Add((count[i].red * 1000 * 1000) + (count[i].green * 1000) + count[i].blue);
}

标签: c#arrayslistcolors

解决方案


移动你的排序。如果您更改了最小值,则只需对数组进行排序。

平均时间:48 毫秒,i7-6700k

ColourCount[] count = new ColourCount[100];
int idx = 0;
for (int r = 0; r < 256; r++)
{
    for (int g = 0; g < 256; g++)
    {
        for (int b = 0; b < 256; b++)
        {
            if (idx < count.Length)
            {
                count[idx].red = (byte)r;
                count[idx].green = (byte)g;
                count[idx].blue = (byte)b;
                count[idx].count = colours[r, g, b];
                idx++;
            }
            else
            {
                if (colours[r, g, b] > count[0].count)
                {
                    count[0].red = (byte)r;
                    count[0].green = (byte)g;
                    count[0].blue = (byte)b;
                    count[0].count = colours[r, g, b];
                    Array.Sort(count, (x, y) => (x.count.CompareTo(y.count)));
                }
            }
        }
    }
}

推荐阅读