0

我在使用此代码时遇到问题。我必须创建一个 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]);
      }

} }

4

1 回答 1

0

对于初学者,您没有正确定义构造函数。

public void PQ() { 
pq= new long[3];
nElems=0;
}

应该更像

PriorityQ() { 
pq= new long[3];
nElems=0;
}
于 2013-02-24T05:23:54.797 回答