优先级队列(堆)PriorityQueue

优先级队列(堆)PriorityQueue

顺序存储:完全二叉树 否则空间浪费 层序遍历

堆:逻辑上是完全二叉树。物理上存在数组上

大根堆:节点的值大于子树中任意节点

小根堆:节点小于子树任意节点。

public class TestHeap {
    public int[] elem;
    public int usedsize;

    public TestHeap(int usedsize) {
        this.elem = new int[10];
    }
    public void adjustdown(int parent, int len) {//每棵树的调整方案  从上往下
        int child = 2 * parent + 1;
        while (child < len) {
            if (child + 1 < len && this.elem[child] < this.elem[child + 1]) {
                child++;
            }
            if (this.elem[child] > this.elem[parent]) {
                int tmp = this.elem[child];
                this.elem[child] = this.elem[parent];
                this.elem[parent] = tmp;
                parent = child;
                child = 2 * parent + 1;
            } else {
                break;
            }
        }
    }
    public void creatHeap(int[] array) {
        for (int i = 0; i < array.length; i++) {
            this.elem[i] = array[i];
            this.usedsize++;
        }
        for (int p = (this.usedsize - 1 - 1) / 2; p >= 0; p--) {
            adjustdown(p, usedsize);
        }
    }
    public void adjustup(int child) {
        int parent = (child - 1) / 2;
        while (child > 0) {
            if (this.elem[child] > this.elem[parent]) {
                int tmp = this.elem[child];
                this.elem[child] = this.elem[parent];
                this.elem[parent] = tmp;
                parent = child;
                child = 2 * parent + 1;
            } else {
                break;
            }
        }
    }
    public void push(int key) {
        if (isFull()) {
            this.elem = Arrays.copyOf(this.elem, this.elem.length * 2);
        }
        this.elem[this.usedsize] = key;
        this.usedsize++;
        adjustup(this.usedsize - 1);
    }
    public boolean isFull() {
        return this.usedsize == this.elem.length;
    }
    //出队的情况
    public void pop() {
        if (isEmpty()) {
            return;
        }
        int tmp = this.elem[0];
        this.elem[0] = this.elem[this.usedsize - 1];
        this.elem[this.usedsize - 1] = tmp;
        this.usedsize--;
        adjustdown(0, usedsize);
    }
    public boolean isEmpty() {
        return this.usedsize == 0;
    }

java默认priorityQueue是小堆

 PriorityQueue<Integer> priorityQueue = new PriorityQueue<>(k, new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o1 - o2;
            }
        });
       
        PriorityQueue<Integer> priorityQueue = new PriorityQueue<>(k, new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o2 - o1;
            }
        });   //大堆

topk问题

 public void topK(int k, int[] a) {
        PriorityQueue<Integer> priorityQueue = new PriorityQueue<>(k, new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o1 - o2;
            }
        });
        for (int i = 0; i < a.length; i++) {
            if (k > 0) {
                priorityQueue.offer(a[i]);
                k--;
            } else {

                if (a[i] > priorityQueue.peek()) {
                    priorityQueue.poll();
                    priorityQueue.offer(a[i]);
                }
            }
            System.out.println(priorityQueue);
        }
    }

堆排序

从小到大建立大堆 从大到小建立小堆

import java.util.Arrays;

public class TestDemo {

    public static void adjustdown( int []array,int parent,int len) {//每棵树的调整方案  从上往下
        int child = 2 * parent + 1;

        while (child < len) {
            if (child + 1 < len && array[child] < array[child + 1]) {
                child++;
            }
            if (array[child] > array[parent]) {
                int tmp = array[child];
                array[child] = array[parent];
                array[parent] = tmp;
                parent = child;
                child = 2 * parent + 1;
            } else {
                break;
            }
        }
    }
    public static void create(int []array){

        for (int p = (array.length-1-1)/2; p >=0 ; p--) {
            adjustdown(array,p,array.length);

        }
    }
    public static  void headSort(int []array){
        create(array);
        int end=array.length-1;
        while(end>0){
            int tmp=array[end];
            array[end]=array[0];
            array[0]=tmp;
            adjustdown(array,0,end);
            end--;
        }

    }

    public static void main(String[] args) {
        int []array={27,15,19,18,28,34,65,49,25,37};
        headSort(array);
        System.out.println(Arrays.toString(array));
    }
}

最后一块石头的重量

class Solution {
    public int lastStoneWeight(int[] stones) {
        PriorityQueue<Integer> priorityQueue = new PriorityQueue<>((o1, o2) -> o2 - o1);
        for (int s : stones) {
            priorityQueue.offer(s);
        }
        while (priorityQueue.size() > 1) {
            int a = priorityQueue.poll();
            int b = priorityQueue.poll();
            if (a > b) {
                priorityQueue.offer(a - b);
            }
        }
        if (priorityQueue.isEmpty()) {
            return 0;
        }
        return priorityQueue.poll();
    }
}

查找和最小的k对数

 class Solution {
        public List<List<Integer>> kSmallestPairs(int[] nums1, int[] nums2, int k) {
            PriorityQueue<List<Integer>> queue = new PriorityQueue<>(k, (o1, o2) -> {
                return (o2.get(0) + o2.get(1)) - (o1.get(0) + o1.get(1));
            });
            for (int i = 0; i < Math.min(nums1.length, k); i++) {
                for (int j = 0; j < Math.min(nums2.length, k); j++) {
                    if (queue.size() == k && nums1[i] + nums2[j] > queue.peek().get(0) + queue.peek().get(1)) {
                        break;
                    }
                    if (queue.size() == k) {
                        queue.poll();
                    }
                    List<Integer> pair = new ArrayList<>();
                    pair.add(nums1[i]);
                    pair.add(nums2[j]);
                    queue.add(pair);
                }
            }
            List<List<Integer>> res = new LinkedList<>();
            for (int i = 0; i < k && !queue.isEmpty(); i++) {
                res.add(queue.poll());
            }
            return res;
        }
    }
}

实现comparable接口重写compareto方法

public class Card implements Comparable<Card> {
public int rank; // 数值
public String suit; // 花色
public Card(int rank, String suit) {
this.rank = rank;
this.suit = suit;
}
// 根据数值比较,不管花色
// 这里我们认为 null 是最小的
@Override
    public int compareTo(Card o) {
if (o == null) {
return 1;
}
return rank - o.rank;
}
public static void main(String[] args){
Card p = new Card(1, "♠");
Card q = new Card(2, "♠");
Card o = new Card(1, "♠");
System.out.println(p.compareTo(o)); // == 0,表示牌相等
System.out.println(p.compareTo(q));// < 0,表示 p 比较小
System.out.println(q.compareTo(p));// > 0,表示 q 比较大
}
}

实现comparator比较器

import java.util.Comparator;
class Card {
public int rank; // 数值
public String suit; // 花色
public Card(int rank, String suit) {
this.rank = rank;
this.suit = suit;
}
}
class CardComparator implements Comparator<Card> {
@Override
public int compare(Card o1, Card o2) {
if (o1 == o2) {
return 0;
}
if (o1 == null) {
return -1;
}
if (o2 == null) {
return 1;
}
return o1.rank - o2.rank;
}
public static void main(String[] args){
Card p = new Card(1, "♠");
Card q = new Card(2, "♠");
Card o = new Card(1, "♠");
// 定义比较器对象
CardComparator cmptor = new CardComparator();
// 使用比较器对象进行比较
System.out.println(cmptor.compare(p, o)); // == 0,表示牌相等
System.out.println(cmptor.compare(p, q)); // < 0,表示 p 比较小
System.out.println(cmptor.compare(q, p)); // > 0,表示 q 比较大
}
}

Comparable.compareTo 需要手动实现接口,侵入性比较强,但一旦实现,每次用该类都有顺序,属于 内部顺序 Comparator.compare 需要实现一个比较器对象,对待比较类的侵入性弱,但对算法代码实现侵入性 强

Object.equals 因为所有类都是继承自 Object 的,所以直接覆写即可,不过只能比较相等与 否

@Override
public boolean equals(Object o) {
// 自己和自己比较
if (this == o) {
return true;
}
// o如果是null对象,或者o不是Card的子类
if (o == null || !(o instanceof Card)) {
return false;
}
// 注意基本类型可以直接比较,但引用类型最好调用其equal方法
Card c = (Card)o;
return rank == c.rank
&& suit.equals(c.suit);
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

力争做大牛的小王

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值