別の方法でプライオリティキューを実装しよう

会うyeol:

私はアイデアが速い挿入をサポートすることで、通常の優先度queue.Hereよりも少し異なる機能プライオリティキューを実装しようとしているが、最も優先度の高い項目へのアクセス遅くしています。それは便利ですどここの場合、Insertメソッドは、新しいアイテムを置き、削除およびPEEK方法は、このように最も優先度の高い項目にキュー全体を検索しなければなりません。

public class MinPriorityQueue {

/** Constructs a new MinPriorityQueue with capacity cap and size 0.
 * 
 * @param cap Capacity of the new queue.
 */
public MinPriorityQueue(int cap) {         

    this.queue = (Comparable []) new Comparable[cap];
    this.size = 0;
    this.cap = cap;
}

int size() {
   return this.size;
}

int capacity() {
   return this.cap;
}

 boolean isEmpty() {
   return this.size==0;
}

boolean isFull() {
    return this.size == cap;       
}

void insert(Comparable e) {
    if (this.size == cap) {
        throw new IllegalStateException();
    }
    queue[size] = e;
    size++;



Comparable remove() {

    if (this.size == 0) {
        throw new IllegalStateException();
    }
    int maxIndex = 0;
    for (int i=1; i<size; i++) { 
        if (queue[i].compareTo (queue[maxIndex]) < 0) { 
            maxIndex = i; 
        } 
    } 
    Comparable result = queue[maxIndex]; 
    size--; 
    queue[maxIndex] = queue[size]; 
    return result;
    }


 /** Returns, but does not remove, the lowest-priority item in the
 * queue.
 * 
 * Complexity: O(n)
 * @return Lowest priority item.
 * @throws IllegalStateException if the queue is empty.
 */
Comparable top()  {
           if (this.size == 0) {
        throw new IllegalStateException();
    }
         /*  int i;
           for (i=0; i < size; i++) {
        if (queue[i].compareTo (size-1) < 0) {
            break;
        }
    }
           return queue[size - 1];*/
    return  queue[size-1]; 
  }



Comparable[] queue; // Contents of the queue

private  int cap;
private int size;    

}

////テストファイル

 /**
     * Test of remove method, of class MinPriorityQueue.
     */
    @Test
    public void testRemove() {
    System.out.println("remove");
    MinPriorityQueue q = new MinPriorityQueue(10);

    boolean throws_exception = false;
    try {
        q.remove();
    } catch (IllegalStateException e) {
        throws_exception = true;
    } catch (Throwable e) {

    }
    assertTrue("remove throws an exception when empty", throws_exception);

    // Permutation of 0...9
    int[] input = {0, 5, 9, 2, 3, 1, 6, 8, 7, 4};

    for (int i : input) {
        q.insert(i);
    }

    assertTrue(q.isFull());

    for (int i = 10; i > 0; --i) {
        assertEquals(q.size(), i);
        Integer x = (Integer) q.remove();
        assertEquals(x, new Integer(10 - i)); // Items are removed in correct order            
    }

    assertTrue(q.isEmpty());
}

/**
 * Test of top method, of class MinPriorityQueue.
 */
@Test
public void testTop() {
    System.out.println("top");
    MinPriorityQueue q = new MinPriorityQueue(10);

    boolean throws_exception = false;
    try {
        q.top();
    } catch (IllegalStateException x) {
        throws_exception = true;
    } catch (Throwable x) {

    }
    assertTrue("top throws an exception when empty", throws_exception);

    int[] input = {0, 5, 9, 2, 3, 1, 6, 8, 7, 4};
    int smallest = 10;
    for (int i : input) {
        q.insert(i);
        if (i < smallest) {
            smallest = i;
        }

        assertEquals(q.top(), smallest);
    }

    for (int i = 0; i < 10; ++i) {
        assertEquals(q.top(), i);
        q.remove();
    }
}    

私は私はmethods.Iたちはこのitem.For最高の優先度を見つけるために、キュー全体を検索することができます方法を見つけ出すことができません実装するためのロジック権利を取得することができませんので削除し、のぞき見を除くすべてのメソッドを実装することができましたループを使用する必要があるためと考えているが、ちょうどロジック権を得ていません

編集:私はremove()メソッドのロジックの権利を取得することができています、ちょうど仕事にポップ()メソッドを取得する必要があります

トビアス:

これを達成する最も簡単な方法は、使用することですjava.util.Listの代わりにしますarrayだから、List(それはまだ速く、インサートを使用するように)、それらを仕分けすることなく、キュー内の要素を維持し、それらの配置を処理します。あなたが実装を使用する場合java.util.ArrayListのためListのインタフェースには、使用してarray他の誰かがすでにほとんどの作業を行っているので、それは、ほぼ正確にあなたがしようとしているが、簡単にされたものですので、内部的に...

クラスを実装することができますのでMinPriorityQueue、このように:

import java.util.ArrayList;
import java.util.List;

//use a generic type argument T here that extends comparable so you can only store objects of a specific type that are comparable to each other
public class MinPriorityQueue<T extends Comparable<T>> {

    private List<T> queue; // Contents of the queue

    private int cap;
    //private int size;

    /**
     * Constructs a new MinPriorityQueue with capacity cap and size 0.
     * 
     * @param cap
     *        Capacity of the new queue.
     */
    public MinPriorityQueue(int cap) {
        this.queue = new ArrayList<T>(cap);
        //this.size = 0;
        this.cap = cap;
    }

    public int size() {
        //return this.size;
        return queue.size();
    }

    public int capacity() {
        return this.cap;
    }

    public boolean isEmpty() {
        //return this.size == 0;
        return queue.isEmpty();
    }

    public boolean isFull() {
        //return this.size == cap;
        return queue.size() == cap;
    }

    public void insert(T e) {
        if (queue.size() == cap) {
            throw new IllegalStateException();
        }
        //queue[size] = e;
        //size++;
        queue.add(e);
    }

    /**
     * Removes and returns the lowest-priority item from the queue.
     * 
     * Complexity: O(n)
     * 
     * @return Lowest priority item that was in the queue.
     * @throws IllegalStateException
     *         if the queue is empty.
     */
    public Comparable<T> remove() {
        if (queue.size() == 0) {
            throw new IllegalStateException();
        }

        /*for (int i = 0; i < this.size; i++) {
            if (this.queue[i] == queue[size]) {
                return i;
            }
        }
        return queue[--size];*/

        //initialize the lowest priority item with the first one in the list
        int lowestPriorityIndex = 0;

        //search every other item in the list to see whether it has a lower priority than the current lowest priority 
        for (int i = 1; i < queue.size(); i++) {
            if (queue.get(i).compareTo(queue.get(lowestPriorityIndex)) < 0) {
                lowestPriorityIndex = i;
            }
        }

        //return and remove the lowest priority item
        return queue.remove(lowestPriorityIndex);
    }

    /**
     * Returns, but does not remove, the lowest-priority item in the queue.
     * 
     * Complexity: O(n)
     * 
     * @return Lowest priority item.
     * @throws IllegalStateException
     *         if the queue is empty.
     */
    public Comparable<T> top() {
        if (queue.size() == 0) {
            throw new IllegalStateException();
        }
        /*  int i;
          for (i=0; i < size; i++) {
        if (queue[i].compareTo (size-1) < 0) {
           break;
        }
        }
          return queue[size - 1];*/


        //initialize the lowest priority item with the first one in the list
        int lowestPriorityIndex = 0;

        //search every other item in the list to see whether it has a lower priority than the current lowest priority 
        for (int i = 1; i < queue.size(); i++) {
            if (queue.get(i).compareTo(queue.get(lowestPriorityIndex)) < 0) {
                lowestPriorityIndex = i;
            }
        }

        //return (but not remove) the lowest priority item
        return queue.get(lowestPriorityIndex);
    }
}

このコードは、あなたの質問に提供されるテストケースのすべてを渡します。

私はまた、例えば、コード(したがって、クラス宣言は今におけるジェネリック型引数を追加しMinPriorityQueue<T extends Comparable<T>>、それが実際の要素を比較するために必要であったため、)。あなたは、一般的な種類について確認することができますここで

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=314697&siteId=1