• 数据结构_堆


    • 定义
      • 堆是一棵完全二叉树
      • 每个父节点大于子节点就是大顶堆,反之就是小顶堆
      • 优先队列可以用堆实现
    • 建堆:自底向上
    • 新增元素:上浮
    • 弹出元素:下沉
    • 例题
      • topK

    参考:数据结构-堆和堆的Java实现

    堆的建立

    在我看来,堆的建立使用了分治法中“合并”的思想:给定两个堆和一个数,合并成一个新的堆。

    给定一个数组,那么堆的建立就是自底向上的,因为一个数就是一个堆,整个大堆依赖于底部的小堆。

    所以把这个数据结构叫做“堆”,很形象。

    可以利用Java中的ArrayList结构实现堆

    import java.util.ArrayList;
    
    public class test {
        public static void main(String[] args) {
            ArrayList<Integer> nums = new ArrayList<>();
            for (int i = 0; i < 10; i++) {
                nums.add(i);
            }
    
            printOnedArray(nums);
    
            for (int i = nums.size() / 2; i >= 0; i--) {
                keepHeapAttrib(nums, i);
            }
    
            printOnedArray(nums);
    
        }
    
        // 保证堆的性质
        public static void keepHeapAttrib(ArrayList<Integer> heap, int index) {
            int left = 2 * index + 1;
            int right = 2 * index + 2;
            int max = index;
            if (left < heap.size() && heap.get(left) > heap.get(max)) max = left;
            if (right < heap.size() && heap.get(right) > heap.get(max)) max = right;
            if (max != index) {
                int temp = heap.get(index);
                heap.set(index, heap.get(max));
                heap.set(max, temp);
                keepHeapAttrib(heap, max);  // 递归解决
            }
        }
    
        public static void printOnedArray(ArrayList<Integer> array) {
            for (int i = 0; i < array.size(); i++) {
                System.out.print(array.get(i) + " ");
            }
            System.out.println();
        }
    }
    
    

    新增元素与弹出元素

    对于大根堆来说,新增元素,就是在堆最后新增一个叶子,然后一直上浮,直到该新增的数为根节点或比父节点小

    对于大根堆来说,弹出元素,就是删除根节点,然后把最后一个叶子取出来,就变成了堆的构建算法。

    例题

    NC119 最小的K个数

  • 相关阅读:
    爬虫再探之mysql简单使用
    python3爬虫再探之EXCEL(续)
    python3爬虫再探之EXCEL
    python3爬虫初探(五)之从爬取到保存
    python3爬虫初探(四)之文件保存
    python3爬虫初探(三)之正则表达式
    python3爬虫初探(二)之requests
    HDU5399——贪心——Too Simple
    ZOJ2829——贪心——Known Notation
    DOS命令
  • 原文地址:https://www.cnblogs.com/ticlab/p/15918316.html
Copyright © 2020-2023  润新知