简体   繁体   English

c++程序的时间和空间复杂度

[英]Time and space complexity of c++ program

#include<iostream>
#include<vector>

using namespace std;

vector <int> removeFirstOrder(const vector<int>& orders)
{
    return vector<int>(++orders.begin() , orders.end());
}

bool isFirstComeFirstServed(const vector<int>& takeOutOrders,
                            const vector<int>& dineInOrders,
                            const vector<int>& servedOrders)
{
    //base case
    if(servedOrders.empty())
    {
        return true;
    }

    if(!takeOutOrders.empty() && takeOutOrders[0]==servedOrders[0])
    {
        return isFirstComeFirstServed(removeFirstOrder(takeOutOrders),
                                      dineInOrders,removeFirstOrder(servedOrders));

    }

    else if(!dineInOrders.empty() && dineInOrders[0]==servedOrders[0])
    {
        return isFirstComeFirstServed(takeOutOrders, removeFirstOrder(takeOutOrders),
                                        removeFirstOrder(servedOrders));

    }

    else
    {
        return false;
    }
}


int main()
{
    vector<int> takeOutOrders{17,8,4};

    vector<int> dineInOrders{12,19,2};
    vector<int> servedOrders{17,8,12,19,24,2};
    isFirstComeFirstServed(takeOutOrders,dineInOrders,servedOrders);



    return 0;
}

My doubt is that here Author of this program says that it has O(n^2) time complexity and O(n^2) space complexity.我怀疑这个程序的作者在这里说它具有 O(n^2) 时间复杂度和 O(n^2) 空间复杂度。

I agree with time complexity of this program because isFirstComeFirstServed function will be called n times which is size of servedOrders Vector Right?我同意这个程序的时间复杂度,因为 isFirstComeFirstServed function 将被调用 n 次,这是 serveOrders 向量的大小,对吗? and removeFirstOrder will be call n times in first function call of isFirstComeFirstServed and n-1 times in second function call of isFirstComeFirstServed and so on till there are no element left in servedOrder Vector Right?并且 removeFirstOrder 将在 isFirstComeFirstServed 的第一个 function 调用中调用 n 次,在 isFirstComeFirstServed 的第二个 function 调用中调用 n-1 次,依此类推,直到 serveOrder 向量中没有元素为止?

But my doubt is that how it can O(n^2) space complexity?但我的疑问是,它如何能够 O(n^2) 空间复杂度? can someone help me to visualize it?有人可以帮我想象一下吗?

Each time removeFirstOrder is called the returned vector is smaller by 1.每次调用removeFirstOrder时,返回的向量都会小 1。

n-1 + n-2 + n-3 + ... + 1

From arithmetic progression rules, the sum is (n+1)*n / 2 which is order n^2.根据算术级数规则,总和为 (n+1)*n / 2,即 n^2 阶。

Tail call optimization could make it O(n) space behind the scene, but it's not guaranteed be performed at all.尾调用优化可以使其在场景后面的空间为 O(n),但根本不能保证执行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM