【问题标题】:Find the greatest right number from the current number in the array algorithm从数组算法中的当前数中找到最大的正确数
【发布时间】:2013-03-08 08:26:31
【问题描述】:

我的算法应该从输入array 中的当前 数字中找到最大 正确的数字,例如,给定以下int[] 输入:

5、9、6、1、3、2

我的算法会输出:

9、6、3、3、2、2

这是我当前的代码:

public static int[] FindGreatestRightNumber(int[] input)
{
    var output = new int[input.Length];
    for (var i = 0; i < input.Length; i++)
    {
        int maxRightNumber = (i == input.Length - 1 ? input[i] : 0);

        for (var j = i+1; j < input.Length; j++)
        {
            var currentNumber = input[j];
            if (maxRightNumber < currentNumber)
                maxRightNumber = currentNumber;
        }
        output[i] = maxRightNumber;
    }

    return output;
}

有人告诉我它可以更快,如何?有什么想法吗?

更新:请不要在你的答案中使用LINQ,我想熟悉使用简单代码解决问题的更快方法,不要@ 987654325@、IEnumerable扩展方法等

【问题讨论】:

  • @Saen:算法是:For each input number, output the greatest of the *following* numbers, or output the input number if there are no following numbers.,至少根据给出的例子。
  • 是的,我想知道为什么输出序列中没有5。鉴于修正后的算法,我不确定它会不会快得多。

标签: c# performance algorithm big-o


【解决方案1】:

您可以从右侧一次通过。诀窍是实现 maxRightVal(n) = max(maxRightVal(n+1), values(n+1))

var output = new int[input.Length];
output[input.Length-1] = input[input.Length-1];

for(int i = input.Length - 2; i >= 0; i--)
    output[i] = output[i+1] > input[i+1] ? output[i+1] : input[i+1];

【讨论】:

  • @Lc。公式中的 n 是什么?
  • @YairNevet 元素索引
  • @lc。准确地说我的代码是 O(n^2) 而你的代码是 O(n) ?
【解决方案2】:

为什么不直接使用Enumerable.Max() 方法?

返回 Int32 值序列中的最大值。

int[] input = new int[] { 5, 9, 6, 1, 3, 2 };
int biggest = input.Max();
Console.WriteLine(biggest); // 9

这是一个DEMO

因为,我现在更清楚地看到了这个问题,所以 VLad 的 answer 看起来是正确的。

【讨论】:

  • 他想要每个数字右边的最大数字。弗拉德的回答更接近正确。
【解决方案3】:

如果你想跳过一些项目并搜索最大值非常简单

int[]arr = {5, 9, 6, 1, 3, 2};
int currentIndex = 2;
int currentValue = 6;
int max = arr.Skip(currentIndex).Where(f => f > currentValue).Max();

EDIT如果你想简单地对一个数组进行排序,那么:

   int[] sorted = arr.OrderByDescending();

【讨论】:

    【解决方案4】:

    从第 (n-2) 个元素开始,维护一个用第 n 个元素初始化的当前最大数组。如果当前元素大于 max 数组中的元素,则继续更新它。继续此操作,直到到达第一个元素。

    【讨论】:

      【解决方案5】:

      这取每个元素右边的最大值;

       int[] input = {5, 9, 6, 1, 3, 2};
       int[] output = input
                  .Take(input.Length-1)
                  .Select( (x,i) => input.Skip(i+1).Max()).ToArray();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-02-07
        • 2012-09-04
        • 2017-10-28
        • 2020-04-13
        • 1970-01-01
        • 2010-09-13
        • 1970-01-01
        相关资源
        最近更新 更多