简体   繁体   English

在线性时间内对特定序列进行排序

[英]Sort a particular sequence in linear time

I am looking at this challenge:我正在考虑这个挑战:

Given a sequence of integers, sorted by their absolute values, return the sequence sorted by their signed value.给定一个整数序列,按它们的绝对值排序,返回按它们的有符号值排序的序列。 The following rules apply:以下规则适用:

  1. You can traverse the sequence in only one direction您只能在一个方向上遍历序列
  2. You cannot randomly access the elements at any position: you have to start from the first element and traverse.您不能在任何位置随机访问元素:您必须从第一个元素开始并遍历。
  3. you can choose any data structure to take the input of the sequence, on the condition that the data structure does not sort the sequence for you您可以选择任何数据结构来接受序列的输入,前提是数据结构不会为您排序序列

How can I solve this with a O(n) time complexity?如何用O(n)时间复杂度解决这个问题?

Here is a possible algorithm using a stack :这是使用堆栈的可能算法:

  • In a first iteration push the negative values on the stack.在第一次迭代中,将负值压入堆栈。
  • Pop values from the stack one by one and output them in that order一个一个地从堆栈中弹出值并按该顺序输出它们
  • In a second iteration select and output the non-negative values.在第二次迭代中选择并输出非负值。

Or with a deque :或者使用双端队列

  • Iterate the sequence only once, and:只迭代一次序列,并且:
  • When the value is negative push the value in front of the deque当值为负时,将值推入双端队列之前
  • When the value is non-negative push the value at the back of the deque当值为非负时,将值推入双端队列的后面
  • Output the deque by pulling values from the front.通过从前面拉取值来输出双端队列。

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

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