【问题标题】:Expressing as Big O notation [duplicate]表示为大 O 符号 [重复]
【发布时间】:2014-09-28 01:41:22
【问题描述】:

所以我知道如果两个while循环只是while(x

    int result = 0;
    int x = 0;
    while (x < n / 2){
            result += arr[x];
            x += 1;
            while (x >= n / 2 && x < n){
                    result += arr[x];
                    x += 1;
            }
     }
     printf("%d\n", result);

【问题讨论】:

  • 为什么不把外循环的代码改写成while (x &lt; n),去掉内循环呢?它将是O(n)
  • 我应该按原样评估它,而不是重写它
  • 提示:线性函数和常数的乘积仍然是线性函数。

标签: c performance algorithm big-o


【解决方案1】:

程序 sn-p 实际上计算数组元素的总和。 如果 n 是元素的数量,那么它运行第一个循环 n/2 次和内部(第二个)循环 n/2 次,总共 n 次,因此,它是 O(n)。 让我们通过一个例子一步一步地解释: 说,

int arr[] = {10, 20, 30, 40, 50}; 
int n = 5;

这些是执行步骤:

1. (first loop) arr[0](10) is added, result becomes 10, x becomes 1
2. (first loop) arr[1](20) is added, result becomes 30, x becomes 2
3. (first loop) arr[2](30) is added, result becomes 60, x becomes 3
4. (first loop) arr[3](40) is added, result becomes 100, x becomes 4
5. (first loop) arr[4](50) is added, result becomes 150, x becomes 5

因此,第一个循环执行 floor(n/2) 次,即 2 次(步骤 1、2) 而在第 2 步,它运行第二个内部循环(x >= n/2 即 x>= 2),第二个循环运行上限(n/2),即 3 次(第 3、4、5 步)和两个循环结束 因此,总体时间复杂度为 O(n)。 但是,这可以做得更简单,例如:

 int result = 0;
 int x = 0;
 while (x < n){
  result += arr[x];
  x += 1;
 }
 printf("%d\n", result);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多