Comparator改写

  • MinQueue 的改写

PriorityQueue<Node> minQ = new PriorityQueue<Node>(new Comparator<Node>() {
    public int compare(Node n1, Node n2) {
        return n1.val - n2.val;
    }
});

或者是

PriorityQueue<Node> minQ = new PriorityQueue<Node>(new Comparator<Node>(){
    public int compare(Node n1, Node n2) {
        if(n1.val < n2.val) return -1;
        else if(n1.val > n2.val) return 1;
        else return 0;
    }
});
  • MaxQueue的改写

PriorityQueue<Node> maxQ = new PriorityQueue<Node>(new Comparator<Node>(){
    public int compare(Node n1, Node n2) {
        return n2.val - n1.val;
    }
});

或者是

PriorityQueue<Node> maxQ = new PriorityQueue<Node>(new Comparator<Node>(){
    public int compare(Node n1, Node n2) {
        if(n1.val < n2.val) return 1;
        else if(n1.val > n2.val) return -1;
        return 0;
    }
});

hellolittleJ17
10 声望11 粉丝