简体   繁体   English

这是在线性时间和恒定空间中吗? (排序数组,让所有的0都在最后,其他数字在前面(解决方案))

[英]Is this in linear time and constant space? (sort array, so that all 0s are at the end, other numbers are at front (solution))

The problem: You are given an array of a bunch of numbers and zeros, sort it so that all the numbers that are not zero , are at the front , and all the numbers at the end are zeros .问题:给你一个由一堆数字和零组成的数组,对它进行排序,使所有不为零的数字都在前面最后的所有数字都是

Question: Does my solution run in Linear time ?问题:我的解决方案是否以线性时间运行? Or not?或不? Also is it constant space or not?也是恒定的空间吗?

#include <iostream>
#include <vector>
#include <stack>
using namespace std;

int main()
{
    cin.tie(0);
    std::ios_base::sync_with_stdio(false);

    vector<int> MyVec;
    int input;
    int i = 0;
    stack<int> mystack;
    stack<int> zerostack;
    while((input = getchar())&& (input!=10))
    {
        if(input != 32)
        {
            MyVec.push_back(input - '0');

            if(MyVec[i] == 0)
                zerostack.push(MyVec[i]);
            else
                mystack.push(MyVec[i]);

            i++;
        }
    }
    MyVec.clear();
    while(!mystack.empty())
    {
         MyVec.push_back(mystack.top());
         mystack.pop();
    }
    while(!zerostack.empty())
    {
         MyVec.push_back(zerostack.top());
         zerostack.pop();
    }
    for(auto a : MyVec)
        cout << a << " ";

    return 0;
}

Not optimized both in time and space complexity.在时间和空间复杂度上都没有优化。 You used extra vector to store and print the elements.您使用额外的向量来存储和打印元素。 You can print those elements without help of vector.您可以在没有矢量的帮助下打印这些元素。

Better you can solve it with deque in C++ STL.更好的是,您可以使用 C++ STL 中的双端队列来解决它。

Answer to your question回答你的问题

  • Your solution does not consume a constant amount of space.您的解决方案不会占用固定数量的空间。
    You store each element you read into MyVec and mystack or zerostack .您将读取的每个元素存储到MyVecmystackzerostack中。 So it'll be at least O(2n) in terms of space consumed, or to simplify it O(n) .因此,就消耗的空间而言,它至少为O(2n) ,或者简化为O(n)

  • Your solution does run in linear time ( O(n) ), but it's not a single-pass algorithm.您的解决方案确实在线性时间 ( O(n) ) 内运行,但它不是单遍算法。
    All your loops will loop N times or less, there are no nested loops, so it'll run in O(n) time.您所有的循环将循环N次或更少,没有嵌套循环,因此它将在O(n)时间内运行。
    However you can still reduce the real runtime of the program by using a better algorithm.但是,您仍然可以通过使用更好的算法来减少程序的实际运行时间。


Potential solutions潜在的解决方案

It's not very clear to me if you need to optimize the entire program or only the part where you sort the vector, so i'll add solutions for both.如果您需要优化整个程序或只优化对向量进行排序的部分,我不太清楚,所以我将为两者添加解决方案。

Whole Program整个节目

If the whole program is to be optimized you can take advantage of the fact that only the zeroes need to be shifted to the back.如果要优化整个程序,您可以利用仅需要将零移到后面的事实。

So if it's not a zero you can directly output it and if it's a zero you just need to remember to output it later after all input has been processed.因此,如果它不是零,您可以直接 output 它,如果它是零,您只需要记住 output 在处理完所有输入后。

eg:例如:

#include <iostream>

int main()
{
    int zeroes = 0;
    char c;
    while((std::cin >> c) && c >= '0' && c <= '9') {
        if(c == '0')
          zeroes++;
        else
          std::cout << c << " ";
    }

    for(int i = 0; i < zeroes; i++)
        std::cout << "0 ";

    return 0;
}

godbolt example螺栓示例

This will run in linear time ( O(n) ) and consume a constant amount of space.这将在线性时间( O(n) )中运行并消耗恒定数量的空间。

Just the sorting of the array只是数组的排序

in case you just need to write a function that sorts a vector, you can apply a similar technique by swapping any zeroes you encounter to the end of the vector.如果您只需要编写一个对向量进行排序的 function,您可以通过将遇到的任何零交换到向量的末尾来应用类似的技术。

This will however not preserve the order of the elements (it's an unstable sorting algorithm).但是,这不会保留元素的顺序(这是一种不稳定的排序算法)。

void sortVector(std::vector<int>& values) {
    int insertPosition = values.size();
    for(int i = 0; i < insertPosition; i++) {
        while(values[i] == 0 && i < insertPosition)
            std::swap(values[i], values[--insertPosition]);
    }
}

godbolt example螺栓示例

This will also run in linear time ( O(n) ) and consumes a constant amount of space (we aren't allocating anything, just shifting stuff around)这也将在线性时间( O(n) )中运行并消耗恒定数量的空间(我们没有分配任何东西,只是移动东西)

It's linear time because each iteration of the while loop decrements the number of times the for loop needs to loop.这是线性时间,因为 while 循环的每次迭代都会减少 for 循环需要循环的次数。

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

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