【问题标题】:Calculating time complexity when number of elements is not given in algorithm算法中未给出元素数量时计算时间复杂度
【发布时间】:2013-06-25 11:10:16
【问题描述】:

我想在链表的末尾找到第 i 个位置的数据。我使用递归编写了这段代码:

节点结构:

struct Node
{
   int data;
   struct Node * next;
}

代码:

int i = 10;

int find ( Node * ptr, unsigned int count )
{
   if( nullptr == ptr )
   {
      ++ count;
      return count;
   }

   count = find ( ptr->next , count );
   if( i == count )
   {
      std::cout << "Successful here: " << ptr->data << std::endl; 
      exit ( -1 ) ;
   }

   else
   {
      ++ count;
      return count ;  
   }
}

我对使用递归关系计算时间复杂度有基本的想法。但我无法编写关系本身。谁能给个方向?

据我了解,我每次都将问题分成一个更少的元素(通过移动到下一个节点)。

所以应该是这样的

T(n) = T(n-1) + 常数

在这种情况下,树方法或任何其他方法会更好吗?

【问题讨论】:

    标签: algorithm recursion complexity-theory time-complexity recurrence


    【解决方案1】:

    这很简单。

    你已经有了时间复杂度的序列

    T(n) = T(n-1) + Constant
    

    你还需要你的结束条件。 首先是你找到元素n。 第二个是您的数组只有 m 个元素,其中 m

    因此,由于您的 count 每次迭代都会增加,我们必须将时间复杂度序列稍微更改为

    T(i,c) = T(i-c, c+1) + Constant
    

    这是因为您将 i 声明为要查找的索引。

    所以现在我们可以写第一个结束条件

    T(0,i) = Constant
    

    而第二个结束条件与T(m,0) 完全相同,因此如果 i > m 我们只需将 i 切换为 m 即可。

    现在假设 Constant 等于 1。

    那么我们得到以下等式

    T(i,0) = T(i-0,1) +1 = T(i-1,2) +2 = T(i-2,3) +3 = T(i-3,4) +4 = .... = i+1
    

    所以复杂度是T((min(i,m),0) = i+1 或T(i,0) 在O(i)。

    您可以将代码更改为

    int find ( Node * ptr, unsigned int i ){
           if( nullptr == ptr )
              return i;
    
           if( i == 0 )
           {
              std::cout << "Successful here: " << ptr->data << std::endl; 
              return 0;
           }
           return find ( ptr->next , --count );
        }
    

    所以你会得到序列T(n) = T(n-1) + Constant

    【讨论】:

      猜你喜欢
      • 2011-06-21
      • 2021-08-25
      • 1970-01-01
      • 1970-01-01
      • 2021-03-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多