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

SortedListそのデータをソートするためだけに一連の値を に追加するのはかなり非効率的です。O(n ^ 2)である「挿入ソート」を効果的に実行しています。最も広く使用されているソート アルゴリズムは O(n*log(n)) です。

その上、最大値だけが必要な場合は、データを 1 回だけループして、O(1) 時間で最大値を計算できます。

Max 値を見つけるには、単純に 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 に答える