我在使用此代码时遇到问题。我必须创建一个 PriorityQ,它具有快速的 O(1) 插入时间,但删除高优先级项目的速度较慢,谁能告诉我我做错了什么?
public class PriorityQ {
private long[] pq;
private int nElems;
public void PQ() {
pq= new long[3];
nElems=0;
}
public boolean isEmpty() { return nElems==0;}
public void insert(long x) {
pq[nElems++]=x;
}
public long remove(long x){
long max = 0;
for (int i = 1; i < nElems; i++)
if (pq[i] == x) {
max = pq[i];
pq[i] = pq[--nElems];
break;
}
return max;
}
public static void main (String []args){
PriorityQ theQ = new PriorityQ();
theQ.insert (10);
theQ.insert (20);
theQ.insert (30);
theQ.remove (10);
for(int i=0; i<theQ.nElems; i++){
System.out.print ("");
System.out.print (theQ.pq[i]);
}
} }