有人可以告诉我这个霍夫曼代码中的空间和时间复杂性,用Bog O符号来解释一下。非常感谢,谢谢。请分别提一下每种方法的Big O,会很棒。感谢。
package HuffmanProject;
import java.util.*;
class MyHCode {
public static void main(String[] args) {
String test = "My name is Zaryab Ali";
int[] FreqArray = new int[256];
for (char c : test.toCharArray()) {
FreqArray[c]++;
}
MyHTree tree = ImplementTree(FreqArray);
System.out.println("CHARACTER\tFREQUENCY\tBINARY EQUIVALEENT CODE");
PrintMyHCode(tree, new StringBuffer());
}
public static MyHTree ImplementTree(int[] FreqArray) {
PriorityQueue<MyHTree> trees = new PriorityQueue<MyHTree>();
for (int i = 0; i < FreqArray.length; i++) {
if (FreqArray[i] > 0) {
trees.offer(new MyHLeaf(FreqArray[i], (char) i));
}
}
while (trees.size() > 1) {
MyHTree FChild = trees.poll();
MyHTree SChild = trees.poll();
trees.offer(new MyHNode(FChild, SChild));
}
return trees.poll();
}
public static void PrintMyHCode(MyHTree tree, StringBuffer prefix) {
if (tree instanceof MyHLeaf) {
MyHLeaf leaf = (MyHLeaf) tree;
System.out.println(leaf.CharValue + "\t\t" + leaf.frequency + "\t\t" + prefix);
}
else if (tree instanceof MyHNode) {
MyHNode node = (MyHNode) tree;
prefix.append('0');
PrintMyHCode(node.left, prefix);
prefix.deleteCharAt(prefix.length() - 1);
prefix.append('1');
PrintMyHCode(node.right, prefix);
prefix.deleteCharAt(prefix.length() - 1);
}
}
}
abstract class MyHTree implements Comparable<MyHTree> {
public int frequency;
public MyHTree(int f) {
frequency = f;
}
public int compareTo(MyHTree tree) {
return frequency - tree.frequency;
}
}
class MyHLeaf extends MyHTree {
public char CharValue;
public MyHLeaf(int f, char v) {
super(f);
CharValue = v;
}
}
class MyHNode extends MyHTree {
public MyHTree left, right;
public MyHNode(MyHTree l, MyHTree r) {
super(l.frequency + r.frequency);
left = l;
right = r;
}
}
答案 0 :(得分:1)
PrintMyHCode()方法遍历左侧和右侧。右子树,直到找到leaft节点。如果树中有n个元素,则此方法的复杂性为O(n)。
ImplementTree()方法将数组中的值添加到树中,然后轮询其子项。 如果数组中有n个元素: 1.此方法中for循环的复杂性将为O(n),因为每个元素都直接添加到树中 2.此方法中while循环的复杂性将为O(logn),假设每个节点至少有两个子节点。
因此,Big O表示法中ImplementTree()方法的总时间复杂度为O(nlogn)。
希望,这个答案适合你。