【问题标题】:Interpreting Big O Loops and arrays解释大 O 循环和数组
【发布时间】:2017-09-20 15:18:55
【问题描述】:

所以,我知道我的想法错了,但我对所有三段代码的回答是它们都是 O(n^2)。

如果我错了,谁能告诉我?

如果是,你能帮我想想如何解决类似的问题。提前谢谢!

    public static int firstLoop(int[] arr) { 

       int sum = 0; int n = arr.length; 
       int limit = n * n; 
       for ( int j = 0; j < limit; j += 2 ) { 
          sum = (sum + arr[j / n] ) % 100; 
      } 
   return sum; }


     public static int withLoop(int[] arr) { 

    int sum = 0; int n = arr.length; 
    int j = 1; 
    int limit = n * n; 
    for ( j= limit - 1; j > 0; j /= 2 ) { 
    sum = (sum + arr[j / n] ) % 100; } 
    return sum; }

   public static int fwLoop(int[] arr)

    {  int sum = 0; 
      int n = arr.length; 
      int limit = n * n; 
      for ( int k = 0; k < limit; k += 2 ) { 
       int t = 1; for ( j = limit - 1; j > 0; j /= 2 ) { 
       t = (t + arr[j / n] ) % 100; 
      } sum = (sum + t + arr[k / n] ) % 200; 
    } return sum; 
 }

【问题讨论】:

  • 请编辑问题并格式化您的代码。
  • 感谢您的编辑!我不知道要对问题进行哪些更改以使其更具针对性..

标签: java arrays time big-o


【解决方案1】:
  1. 如您所说,第一段代码在 O(n^2) 中运行,因为 limit 的大小为 n^2

  2. 然而第二个是j/=2,它将每次limit的长度除以2,因此循环将运行k次k=log(n^2) = 2log(n),因此它是O(log(n))顺序

  3. 第三个是第一个和第二个的组合,运行在O((n^2)*log(n))时间

【讨论】:

  • 感谢您的解释!超级有帮助!!我需要对第二个进行一些练习,确定它何时是 log n。有没有我可以练习的类似代码?
  • @chocolateAndMath 这样想,你将n^2 除以2k 次,直到它变成1(n^2)/(2^(k))=1 简化这个,它给出k=2*log(n) ,有很多排序和搜索算法都有log(n)
  • 我现在明白多了。谢谢你奥斯瓦尔德!
猜你喜欢
  • 2017-01-02
  • 2018-10-15
  • 2016-01-22
  • 2014-01-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-03
  • 1970-01-01
相关资源
最近更新 更多