在少于O(n)的时间内反转数组的子数组

时间:2011-12-01 12:39:19

标签: arrays algorithm linked-list reverse

如何在少于O(n)的时间内反转数组(或任何其他数据结构,如链表(不是双重))的子数组(比如从第i个索引到第j个索引) ? O(n)时间消耗是微不足道的。(我想在数组上多次进行这种反转,比如从开始开始并将其反转n次(每次,前进一个索引,然后再将其反转),所以应该有一种方法,它的摊销分析会给我们一个小于O(n)的时间消耗,任何想法?
谢谢提前:))

3 个答案:

答案 0 :(得分:4)

我认为你想用错误的方法解决这个问题。我想你想要整体改进算法,而不是O(n)反转的东西。因为那是不可能的。如果你必须考虑n个元素中的每一个,你总是有O(n)。

正如我所说,你能做的是改进O(n ^ 2)算法。你可以在O(n)中解决这个问题: 假设我们有这个列表:

a b c d e

然后使用您的算法修改此列表:

e d c b a
e a b c d

等等..最后你有这个:

e a d b c

如果有两个指针来自数组的两端并在指针之间交替(增量/减量/获取值),则可以获取此列表。这给了你整个程序的O(n)。

该算法的更详细说明:

使用上一个列表,我们希望按以下顺序排列元素:

a b c d e
2 4 5 3 1

所以你创建了两个指针。一个指向列表的开头,另一个指向结尾:

a b c d e
^       ^
p1      p2

然后算法的工作原理如下:

1. Take the value of p2
2. Take the value of p1
3. Move the pointer p2 one index back
4. Move the pointer p1 one index further
5. If they point to the same location, take the value of p1 and stop.
   or if p1 has passed p2 then stop.
   or else go to 1.

答案 1 :(得分:0)

正如duedl0r所提到的,O(n)是你的最低要求。你必须将n个项目移动到新的位置。

由于你提到了一个链表,这里有一个O(n)解决方案。

如果您移动所有节点并反转它们的方向,则将末端绑定到列表的其余部分,子列表将反转。所以:

1->2->3->4->5->6->7->8->9

逆转4到7会改变:

4->5->6->7

成:

4<-5<-6<-7

然后让3指向7并让4指向8。

有些复制duedl0r的格式是为了保持一致性:

 1. Move to the item before the first item to reorder(n steps)
 2. remember it as a (1 step)
 3. Move to the next item (1 step)
 4. Remember it as b (1 step)

while not at the last item to reorder: (m times)
 5. Remember current item as c (1 step)
 6. Go to next item (1 step)
 7. Let the next item point to the previous item (1 step)

having reached the last item to reorder:
 8. let item a point to item c (1 step)

if there is a next item:
 9. move to next item (1 step)
 10. let item b point to current item (1 step)

那是O(n + 1 + 1 + 1 + m *(1 + 1 + 1)+ 1 + 1 + 1)。 如果没有Big O中不允许的所有数字,那就是O(n + m),可以称为O(n + n),可以称为O(2n)。

那就是O(n)。

答案 2 :(得分:0)

对于给定的数组,您可以执行O(n)时间。这里l表示起始索引,r表示结束。所以我们需要将子阵列从r转换为l。

public void reverse(int[] arr, int l, int r)
  {
      int d = (r-l+1)/2;
      for(int i=0;i<d;i++)
      {
         int t = arr[l+i];
         arr[l+i] = arr[r-i];
         arr[r-i] = t;
      }
    // print array here 
  }