【发布时间】:2017-09-19 10:38:52
【问题描述】:
我在 Java 中创建了一个非常简单的链表:
public class LinkedList {
class Node {
public Node next;
public int item;
public Node (int item) {
this.item = item;
}
}
int listSize = 0;
Node first = null;
Node last = null;
public void add(int n) {
Node node = new Node(n);
if (first == null) {
first = node;
} else {
last.next = node;
}
last = node;
listSize++;
}
}
所以在主类中,我将以随机顺序将元素添加到链表中。但是如何创建一个计算链表中反转次数的方法?
到目前为止,我已经设法以 O(N^2) 的运行时间来实现它:
public int inversionCount() {
int count = 0;
Node current = this.first;
for (int i = 0; i <= this.listSize - 2; i++) {
Node next = current.next;
for (int j = i + 1; j < this.listSize; j++) {
if (current.item > next.item) {
System.out.print("(" + current.item + "," + next.item + ")" + " ");
count += 1;
}
next = next.next;
}
current = current.next;
}
return count;
}
然而,正如我所说,这个算法的运行时间是 O(N^2)。我正在尝试实现 O(NlogN) 的运行时间。如何实现?
【问题讨论】:
-
如果您将列表排序为(值,原始索引)的列表 - O(N log N)。那么索引和原始索引可能与反转计数具有数学关系。或者这样。快乐令人费解。如果事实上排序算法本身可以计算并行数组反转计数中的反转。
-
在你的
add方法中,last.next = Node;不应该是first.next = Node;吗?
标签: java algorithm linked-list time-complexity inversion