【问题标题】:O(n log n) Time Complexity Algorithm?O(n log n) 时间复杂度算法?
【发布时间】:2015-06-12 14:21:21
【问题描述】:

我创建了这个算法来找到 3 个数字之间的最佳交易。它通过该程序并找到卖出、买入和从股票中获利的最佳日子。我需要解释所使用的算法以及时间复杂度如何为 O(n log n),但我在确定这一点时遇到了很多麻烦。我希望有人可以解释 O(n log n) 并将其与我的方法联系起来。

这是我的方法:

public static Trade bestTrade(int[] a) 
   {
      int lowest = a[0];
      int lowestIndex = 0;
      int highest = a[a.length - 1];
      int highestIndex = a.length - 1;
      int profit = 0;

      for(int i = 1; i < a.length; i++) 
      {
         if (a[i] < lowest && i < highestIndex) 
         {
            lowest = a[i];
            lowestIndex = i;
         }  
      }

      for(int i = a.length - 2; i >= 0; i--) 
      {
         if (a[i] > highest && i > lowestIndex) 
         {  
            highest = a[i];   
            highestIndex = i;
         }  
      }

      for(int i = 1; i < a.length; i++) 
      {
         if (a[i] < lowest && i < highestIndex) 
         {   
            lowest = a[i];   
            lowestIndex = i;
         }  
      }

      if (highestIndex > lowestIndex) 
      {
         profit = highest - lowest;
         return new Trade(lowestIndex, highestIndex, profit);
      }

      return new Trade(lowestIndex, highestIndex, profit);
   }

}

【问题讨论】:

  • 乍一看,它实际上是 O(3n),相当于 O(n)。
  • 在我看来是 O(n)。所有循环都是线性的。没有递归。
  • 所以要使时间复杂度 O(n log n) 我需要组合我的 for 循环?抱歉,对这个有点陌生。
  • @kids O(n log n) 算法通常是涉及递归的分而治之的排序算法。嵌套循环通常会产生 n 平方的运行时间。

标签: java algorithm time big-o


【解决方案1】:

O(n)

它与a.length的数量成正比。每次运行 for 函数时,都会遍历每一天的数据。如果有一种方法可以使进程数增加超过纯数(嵌套 fors),那么它可能是 O(n log n) 或 O(n^2)。但在这种情况下,很明显它只是 n 的大 O。

【讨论】:

  • 所以我需要一组嵌套的 fors 来创建 O(n log n) 复杂度? @AlexG
  • O(n log n) 看起来像这样: for(int i =1; i
【解决方案2】:

尝试自己寻找答案。将来会有很大帮助。这看起来也像 O(N) ,我不确定你为什么确信它是 O(NlogN)。

此链接可能有用, http://pages.cs.wisc.edu/~vernon/cs367/notes/3.COMPLEXITY.html

【讨论】:

    【解决方案3】:

    复杂度是O(n),其中n是数组a的长度。

    你在a上循环3次,所以运行时间大约是3n,所以它的顺序是n:O(n)。

    【讨论】:

      【解决方案4】:

      这个函数的 O(n) 优于 O(n log n) 。 一般来说,你只看循环,因为没有嵌套循环,你只有循环遍历 a 的所有元素。函数被认为是 n。

      【讨论】:

        猜你喜欢
        • 2011-07-09
        • 2015-05-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-06-22
        相关资源
        最近更新 更多