为什么ArrayList删除O(n)中的功能而不是O(n * n)

时间:2018-02-10 06:10:12

标签: algorithm

请告诉我下面函数Remove的时间复杂度是O(n)还是O(n * n)?

它删除集合中与值提供的值匹配的第一个项目,如果删除了值,则返回true。否则返回false

public bool Remove(T item) 
{ 
    for (int i = 0; i < Count; i++) 
    {
       if (_items[i].Equals(item)) 
       {
         RemoveAt(i); 
         return true; 
       }
    } 
    return false; 
}

public void RemoveAt(int index)
{
    if (index >= Count)
    {
        throw new Exception("Index out of Range");
    }

    var sourceIndex = index + 1;
    Array.Copy(_array, sourceIndex, _array, index, _array.Length - sourceIndex);

    Count--;
}

2 个答案:

答案 0 :(得分:0)

public bool Remove(T item) 
{ 
    for (int i = 0; i < Count; i++) // say count = n. this loop will run n times.
    {
       if (_items[i].Equals(item)) // say if operation takes 10 units of time
       {
         RemoveAt(i);  
         return true;  // say this operation takes 2 units of time
       }
    } 
    return false; // say this operation takes 2 units of time
}

public void RemoveAt(int index) {
    if (index >= Count) // say this operation takes 10 units of time
    {
        throw new Exception("Index out of Range"); // say this operation takes 4 units of time
    }

    var sourceIndex = index + 1; // say this operation takes 2 units of time
    Array.Copy(_array, sourceIndex, _array, index, _array.Length - sourceIndex); // say this operation takes 10 units of time

    Count--; // say this operation takes 5 units of time
}

这意味着RemoveAt需要10 + 4 + 2 + 10 + 5个单位时间= 31个单位时间 并且Remove需要n *(10 + 31 + 2)个时间单位= n * 43个单位时间。

任何花费一定时间的操作称为O(1)操作。因此,Remove需要n * O(1)个时间单位,大约为O(n)

答案 1 :(得分:0)

您的算法最多需要 O n )步骤:

  • RemoveAt中复制数组最多需要 O n )步骤。
  • 遍历Remove中的数组也需要最多 O n )步骤。
  • 由于RemoveAt最多从Remove调用一次,因此总运行时间为: O n )+ 1 * O n )= O 2n )= O n )。
相关问题