1

以下のコードのように、3つのソートされた配列から最大5つの数を取得する他の最良の方法はありますか?

アップデート:

  1. 以下のコードで結果が得られますが、これが唯一の方法かどうかはわかりません

  2. 入力配列に重複が含まれている可能性がありますが、結果は重複してはなりません

  3. 効率的とは、結果を得るまでに必要な反復回数が少ないことを意味します。

  4. linq固有の回答を探しています。

private void Take5MaxNumbers()
{
    var a1 = new[] { 10, 25, 45, 65, 76 };
    var a2 = new[] { 32, 43, 54, 62, 78, 85, 93, 102 };
    var a3 = new[] { 54, 74, 98, 105 };


    var finalArray = a1.Union(a2).Union(a3).OrderByDescending(x => x).Take(5);

    foreach (var item in finalArray)
    {
        Console.Write(item + " ");
    }
}

// Output:
105 102 98 93 85
4

3 に答える 3

2

Iterate 5 steps of merge sort for 3 arrays: this could be accomplished with an array of three elements holding the largest values of each array, then finding the maximum and index of the maximum. (if the index is 2 (from 0..2), replace that element from the last presorted array.)

The steps to do this [efficiently] with linq would probably require these steps --

于 2013-03-04T06:12:56.393 に答える
1

The best way to find out the top 5 element from sorted array is to compare last element of each array get max and the compare last element of each array leaving the previous founded element.

below is the two way for doing this task first one is using only basic types and is the most efficient way, no extra loop no extra comparison no extra memory consumption, just pass the index of elements that need to be match with another one and calculate which is the next index to be match for each given array.

Fist one is this : go through the link :-

Most efficient way to find max top 5 number from three given sorted array

Second one is this :-

int[] Array1 = { 09, 65, 87, 89, 888 };
int[] Array2 = { 1, 13, 33, 49, 921 };
int[] Array3 = { 22, 44, 66, 88, 110 };

int [] MergeArr = Array1.Concat(Array2).Concat(Array3).ToArray();
Array.Sort(MergeArr);
int [] Top5Number = MergeArr.Reverse().Take(5).ToArray() 

Most efficient way to find max top 5 number from three given sorted array

于 2013-09-13T09:26:59.083 に答える
0

You can take the top 5 elements in each array and then finally order by descending.

var a1_5 = a1.Reverse().Take(5).Reverse();
var a2_5 = a2.Reverse().Take(5).Reverse();
var a3_5 = a3.Reverse().Take(5).Reverse();
var resultArray = (a1_5.Union(a2_5)).Union(a3_5).OrderByDescending(x=>x).Take(5);

This way your sorting method "OrderByDescending" will have less inputs to process and better performance.

于 2013-03-04T06:45:34.953 に答える