数据结构 优先队列Backtraxe 收录于 类别 数据结构 2022-08-30 2022-09-02 约 602 字 预计阅读 2 分钟 目录 介绍大顶堆小顶堆参考警告本文最后更新于 2022-09-02,文中内容可能已过时。介绍大顶堆 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 class MaxPQ { private int[] data; private int n; // 当前元素个数,因为索引从 1 开始,也是最后一个元素的下标 public MaxPQ(int maxN) { data = new int[maxN + 1]; } public MaxPQ(int[] nums) { data = new int[nums.length + 1]; for (int x : nums) add(x); } public void add(int x) { if (n == data.length - 1) return; data[++n] = x; swim(n); } public int getMax() { if (isEmpty()) return -1; return data[1]; } public int pollMax() { if (isEmpty()) return -1; swap(1, n--); sink(1); return data[n + 1]; } public int size() { return n; } public boolean isEmpty() { return n == 0; } private void swim(int k) { if (k <= 1 || k > n) return; while (k > 1 && data[k / 2] < data[k]) { swap(k / 2, k); k /= 2; } } private void sink(int k) { if (k < 1 || k > n / 2) return; while (k * 2 <= n) { int i = k * 2; if (i + 1 <= n && data[i] < data[i + 1]) i++; if (data[k] >= data[i]) break; swap(k, i); k = i; } } private void swap(int i, int j) { int temp = data[i]; data[i] = data[j]; data[j] = temp; } } 小顶堆 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 class MinPQ { private int[] data; private int n; // 当前元素个数,因为索引从 1 开始,也是最后一个元素的下标 public MinPQ(int maxN) { data = new int[maxN + 1]; } public MinPQ(int[] nums) { data = new int[nums.length + 1]; for (int x : nums) add(x); } public void add(int x) { if (n == data.length - 1) return; data[++n] = x; swim(n); } public int getMin() { if (isEmpty()) return -1; return data[1]; } public int pollMin() { if (isEmpty()) return -1; swap(1, n--); sink(1); return data[n + 1]; } public int size() { return n; } public boolean isEmpty() { return n == 0; } private void swim(int k) { if (k <= 1 || k > n) return; while (k > 1 && data[k / 2] > data[k]) { swap(k / 2, k); k /= 2; } } private void sink(int k) { if (k < 1 || k > n / 2) return; while (k * 2 <= n) { int i = k * 2; if (i + 1 <= n && data[i] > data[i + 1]) i++; if (data[k] <= data[i]) break; swap(k, i); k = i; } } private void swap(int i, int j) { int temp = data[i]; data[i] = data[j]; data[j] = temp; } } 参考