1

我目前正在循环中使用 SortedList 以降序对某些值进行排序:

for(...)
{
    float rawValue;
    float offset;
    sortedList.Add(rawValue + offset, index);
}

我有兴趣找出sortedList[0](即具有最高 rawValue+offset 的条目)是否也是最高条目,如果我们按照它们的原始值对条目进行排序,而没有偏移量?

显而易见的解决方案是在同一个循环中填充另一个 sortedRawValuesList,但我认为有更快、更高效的方法来实现这一点?

谢谢!

4

3 回答 3

4

您不能在迭代时简单地跟踪最高的 rawValue 吗?如果偏移量在每次迭代中发生变化,您可能还想保存偏移量。

float highestRawVal = float.MinVal;
float offset_ForHighestRawVal = float.MinVal;
for(...)
{
    float rawValue;
    float offset;
    sortedList.Add(rawValue + offset, index);
    if(highestRawVal < rawVal)
    {
        highestRawVal = rawValue;
        offset_ForHighestRawVal = offset;
    }
}

if (highestRawVal + offset_ForHighestRawVal == sortedList[0])
    Console.WriteLine("They Match");

然后你可以简单地检查它们是否匹配。

于 2012-10-31T18:52:39.303 回答
2

将一堆值添加到 aSortedList只是为了对数据进行排序是相当低效的。您实际上是在进行“插入排序”,即 O(n^2)。最广泛使用的排序算法是 O(n*log(n))。

最重要的是,如果您只需要最大值,您可以只循环一次数据并在 O(1) 时间内计算最大值。

要找到最大值,只需使用 LINQ 的Max函数:

IEnumerable<X> data = ...;

float max = data.Max(item => doSomeComputation(item));

要获取生成最大值的项目,您可以使用 MaxBy。(不幸的是 .NET 不直接发布它,您需要自己编写/添加它。)

X maxItem = data.MaxBy(item => doSomeComputation(item));

public static TSource MaxBy<TSource, TKey>(this IEnumerable<TSource> source
    , Func<TSource, TKey> selector
    , IComparer<TKey> comparer = null)
{
    if (comparer == null)
    {
        comparer = Comparer<TKey>.Default;
    }
    using (IEnumerator<TSource> iterator = source.GetEnumerator())
    {
        if (!iterator.MoveNext())
        {
            throw new ArgumentException("Source was empty");
        }

        TSource maxItem = iterator.Current;
        TKey maxValue = selector(maxItem);

        while (iterator.MoveNext())
        {
            TKey nextValue = selector(iterator.Current);
            if (comparer.Compare(nextValue, maxValue) > 0)
            {
                maxValue = nextValue;
                maxItem = iterator.Current;
            }
        }
        return maxItem;
    }
}
于 2012-10-31T18:57:14.223 回答
1

为什么不简单地利用 LINQ 为您做这种事情呢?

var sortedList = // Get List

var withOffsets = sortedList.Select(x => new { Original = x, Offset = x + offset }).OrderBy(x => x.Offset);

if(sortedList.First() == withOffsets.First())
   // True!
于 2012-10-31T18:52:22.790 回答