问题
So basically, Im asked to sort a queue, and i can only use one helper queue , and am only allowed constant amount of additional memory.
How would i sort a queue using only one additional queue ?
回答1:
Personally, I don't like interview questions with arbitrary restrictions like this, unless it actually reflects the conditions you have to work with at the company. I don't think it actually finds qualified candidates or rather, I don't think it accurately eliminates unqualified ones. When I did technical interviews for my company, all of the questions were realistic and relevant. Setting that aside.
While there are surely several ways to solve this, and using recursion is certainly one, I would hope that if you tried to solve it with recursion they would have asked you to do it over without recursion, considering they are placing limits on the memory you can use and the data structures. Otherwise, they might as well as given you two queues, a stack and as much memory as you want.
Here is an example of one way to solve it. At the end of this, queueB should be sorted. It uses just one extra local variable. This was done in C#.
queueB.Enqueue(queueA.Dequeue());
while (queueA.Count > 0)
{
int next = queueA.Dequeue();
for (int i = 0; i < queueB.Count; ++i)
{
if (queueB.Peek() < next)
{
queueB.Enqueue(queueB.Dequeue());
}
else
{
queueB.Enqueue(next);
next = queueB.Dequeue();
}
}
queueB.Enqueue(next);
}
来源:https://stackoverflow.com/questions/28822952/how-would-i-sort-a-queue-using-only-one-additional-queue