【问题标题】:The complexity of the following code is O(n) , but if arr [ i ] < arr [ j ] is changed as arr [ i ] < = arr [ j ], Still the complexity remain same?以下代码的复杂度是 O(n) ,但是如果将 arr [ i ] < arr [ j ] 更改为 arr [ i ] < = arr [ j ],复杂度仍然保持不变吗?
【发布时间】:2021-01-02 07:26:41
【问题描述】:
void fun(int n, int arr[])
{
    int i = 0, j = 0;
    for(; i < n; ++i)
        while(j < n && arr[i] < arr[j])
            j++;
}

如果将 arr[i]

【问题讨论】:

    标签: algorithm performance loops time-complexity big-o


    【解决方案1】:

    无论是arr[i] &lt; arr[j] 还是arr[i] &lt;= arr[j],两个答案都具有相同的运行时间O(n),因为i 计数器只会增加n 次,而while loop 条件最多为真ntimes,因为j最多增加n倍(参考j &lt; n)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-16
      • 1970-01-01
      • 2017-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-26
      • 1970-01-01
      相关资源
      最近更新 更多