我在 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) 的运行时间。如何做到这一点?