算法与数据结构全阶班-左程云版(二)基础阶段之4.堆和比较器(下)

简介: 本文主要介绍了堆和比较器:堆包括大根堆和小根堆;比较器的实质就是重载比较运算符,可以用于普通方式的排序和自定义的排序。

2.比较器

比较器:

1)比较器的实质就是重载比较运算符

2)比较器可以很好的应用在特殊标准的排序上;

3)比较器可以很好的应用在根据特殊标准排序的结构上;

4)写代码变得异常容易,还用于范型编程。

先实现应用在特殊标准的排序,如下:

package heap04;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.TreeMap;
/**
 * @author Corley
 * @date 2021/10/13 17:22
 * @description LeetCodeAlgorithmZuo-heap04
 */
public class CustomComparator {
    static class Student {
        private final String name;
        private final int id;
        private final int age;
        public Student(String name, int id, int age) {
            this.name = name;
            this.id = id;
            this.age = age;
        }
        @Override
        public String toString() {
            return "Student{" +
                    "name='" + name + '\'' +
                    ", id=" + id +
                    ", age=" + age +
                    '}';
        }
    }
    /*
    * id升序比较器
    * */
    static class IdAscendingComparator implements Comparator<Student> {
        @Override
        public int compare(Student o1, Student o2) {
            return o1.id - o2.id;
        }
    }
    /*
    * 年龄降序比较器
    * */
    static class AgeDescendingComparator implements Comparator<Student> {
        @Override
        public int compare(Student o1, Student o2) {
            return o2.age - o1.age;
        }
    }
    /*
    * 复杂比较器,年龄降序、id升序
    * */
    static class AgeDescendingIdAscedingComparator implements Comparator<Student> {
        @Override
        public int compare(Student o1, Student o2) {
            return o1.age != o2.age ? o2.age - o1.age : o1.id - o2.id;
        }
    }
    public static void main(String[] args) {
        Student student1 = new Student("A", 3, 40);
        Student student2 = new Student("B", 2, 21);
        Student student3 = new Student("C", 4, 12);
        Student student4 = new Student("D", 5, 62);
        Student student5 = new Student("E", 3, 42);
        Student[] studentArray = new Student[] {student1, student2, student3, student4, student5};
        Arrays.sort(studentArray, new IdAscendingComparator());
        System.out.println(Arrays.toString(studentArray));
        System.out.println("-------------------------------------");
        ArrayList<Student> studentList = new ArrayList<>();
        studentList.add(student1);
        studentList.add(student2);
        studentList.add(student3);
        studentList.add(student4);
        studentList.add(student5);
        studentList.sort(new AgeDescendingComparator());
        System.out.println(studentList);
        System.out.println("-------------------------------------");
        TreeMap<Student, String> studentMap = new TreeMap<>(new AgeDescendingIdAscedingComparator());
        studentMap.put(student1, "我是学生1,我的名字叫A");
        studentMap.put(student2, "我是学生2,我的名字叫B");
        studentMap.put(student3, "我是学生3,我的名字叫C");
        studentMap.put(student4, "我是学生4,我的名字叫D");
        studentMap.put(student5, "我是学生5,我的名字叫E");
        System.out.println(studentMap.keySet());
    }
}

输出:

[Student{name='B', id=2, age=21}, Student{name='A', id=3, age=40}, Student{name='E', id=3, age=42}, Student{name='C', id=4, age=12}, Student{name='D', id=5, age=62}]
-------------------------------------
[Student{name='D', id=5, age=62}, Student{name='E', id=3, age=42}, Student{name='A', id=3, age=40}, Student{name='B', id=2, age=21}, Student{name='C', id=4, age=12}]
-------------------------------------
[Student{name='D', id=5, age=62}, Student{name='E', id=3, age=42}, Student{name='A', id=3, age=40}, Student{name='B', id=2, age=21}, Student{name='C', id=4, age=12}]

再实现应用在根据特殊标准排序的结构,如下:

package heap04;
import java.util.Comparator;
import java.util.PriorityQueue;
/**
 * @author Corley
 * @date 2021/10/13 14:56
 * @description LeetCodeAlgorithmZuo-heap04
 */
public class HeapUse {
    /*
     * 整型比较器
     * */
    static class IntegerComparator implements Comparator<Integer> {
        @Override
        public int compare(Integer o1, Integer o2) {
            return o2 - o1;
        }
    }
    public static void main(String[] args) {
        // PriorityQueue<Integer> heap = new PriorityQueue<>();
        // 大根堆
        PriorityQueue<Integer> heap = new PriorityQueue<>(new IntegerComparator());
        heap.add(5);
        heap.add(7);
        heap.add(3);
        heap.add(0);
        heap.add(5);
        heap.add(2);
        while (!heap.isEmpty()) {
            System.out.println(heap.poll());
        }
    }
}

可以看到,用PriorityQueue实现了大根堆。

语言提供的堆结构vs手写的堆结构:

取决于有没有动态改信息的需求;

语言提供的堆结构,如果你动态改数据,不保证依然有序

手写堆结构,因为增加了对象的位置表,所以能够满足动态改信息的需求。

思路如下:

2345_image_file_copy_146.jpg

实现如下:

package heap04;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.PriorityQueue;
/**
 * @author Corley
 * @date 2021/10/13 19:24
 * @description LeetCodeAlgorithmZuo-heap04
 */
public class CustomHeap {
    static class SelfHeap<T> {
        private final ArrayList<T> heap;                // 小根堆
        private final HashMap<T, Integer> indexMap;
        private int heapSize;
        private final Comparator<? super T> comparator;
        public SelfHeap(Comparator<? super T> comparator) {
            heap = new ArrayList<>();
            indexMap = new HashMap<>();
            heapSize = 0;
            this.comparator = comparator;
        }
        public boolean isEmpty() {
            return heapSize == 0;
        }
        public int size() {
            return heapSize;
        }
        public boolean contains(T key) {
            return indexMap.containsKey(key);
        }
        public void push(T value) {
            heap.add(value);
            indexMap.put(value, heapSize);
            heapInsert(heapSize++);
        }
        public T pop() {
            T ans = heap.get(0);
            int end = heapSize - 1;
            swap(0, end);
            heap.remove(end);
            indexMap.remove(ans);
            heapify(0, --heapSize);
            return ans;
        }
        public void resign(T value) {
            int valueIndex = indexMap.get(value);
            heapInsert(valueIndex);
            heapify(valueIndex, heapSize);
        }
        private void heapInsert(int index) {
            while (comparator.compare(heap.get(index), heap.get((index - 1) / 2)) < 0) {
                swap(index, (index - 1) / 2);
                index = (index - 1) / 2;
            }
        }
        private void heapify(int index, int heapSize) {
            int left = index * 2 + 1;
            while (left < heapSize) {
                int smallest = left + 1 < heapSize && (comparator.compare(heap.get(left + 1), heap.get(left)) < 0) ?
                        left + 1 : left;
                smallest = comparator.compare(heap.get(smallest), heap.get(index)) < 0 ? smallest : index;
                if (smallest == index) {
                    break;
                }
                swap(smallest, index);
                index = smallest;
                left = index * 2 + 1;
            }
        }
        private void swap(int i, int j) {
            T t1 = heap.get(i);
            T t2 = heap.get(j);
            heap.set(i, t2);
            heap.set(j, t1);
            indexMap.put(t1, j);
            indexMap.put(t2, i);
        }
    }
    public static class Student {
        public int classNo;
        public int age;
        public int id;
        public Student(int c, int a, int i) {
            classNo = c;
            age = a;
            id = i;
        }
    }
    public static class StudentComparator implements Comparator<Student> {
        @Override
        public int compare(Student o1, Student o2) {
            return o1.age - o2.age;
        }
    }
    public static void main(String[] args) {
        Student s1 = new Student(2, 50, 11111);
        Student s2 = new Student(1, 60, 22222);
        Student s3 = new Student(6, 10, 33333);
        Student s4 = new Student(3, 20, 44444);
        Student s5 = new Student(7, 72, 55555);
        Student s6 = new Student(1, 14, 66666);
        SelfHeap<Student> myHeap = new SelfHeap<>(new StudentComparator());
        myHeap.push(s1);
        myHeap.push(s2);
        myHeap.push(s3);
        myHeap.push(s4);
        myHeap.push(s5);
        myHeap.push(s6);
        while (!myHeap.isEmpty()) {
            Student cur = myHeap.pop();
            System.out.println(cur.classNo + "," + cur.age + "," + cur.id);
        }
    }
}

之所以这种方式可以实现修改其中的元素后能重新排序,一个重要的原因是因为存入堆中的其实只是元素的引用,在修改元素的属性之后,引用对应的堆区对象的属性就会发生改变,所以相当于堆中的某个元素的属性发生变化,此时如果以这个属性为排序依据,则需要调用heapInsert和heapify方法对堆进行调整,以满足大根堆或小根堆的条件。

在实际使用中,选择堆时,如果只是单纯向堆中加入或取元素,则可以直接使用系统提供的堆;

如果需要对堆中的元素进行修改,则需要自己实现堆和对应的比较器。

总结

堆是在完全二叉树的基础上实现的,分为大根堆和小根堆,堆排序实现了O(N*LogN)的时间复杂度。比较器可以很好的应用在特殊标准的排序和根据特殊标准排序的结构上。

目录
打赏
0
0
0
0
2
分享
相关文章
|
3天前
|
算法系列之数据结构-二叉树
树是一种重要的非线性数据结构,广泛应用于各种算法和应用中。本文介绍了树的基本概念、常见类型(如二叉树、满二叉树、完全二叉树、平衡二叉树、B树等)及其在Java中的实现。通过递归方法实现了二叉树的前序、中序、后序和层次遍历,并展示了具体的代码示例和运行结果。掌握树结构有助于提高编程能力,优化算法设计。
32 9
 算法系列之数据结构-二叉树
|
2天前
|
算法系列之数据结构-二叉搜索树
二叉查找树(Binary Search Tree,简称BST)是一种常用的数据结构,它能够高效地进行查找、插入和删除操作。二叉查找树的特点是,对于树中的每个节点,其左子树中的所有节点都小于该节点,而右子树中的所有节点都大于该节点。
43 22
C 408—《数据结构》算法题基础篇—链表(下)
408考研——《数据结构》算法题基础篇之链表(下)。
88 29
C 408—《数据结构》算法题基础篇—链表(上)
408考研——《数据结构》算法题基础篇之链表(上)。
99 25
C 408—《数据结构》算法题基础篇—数组(通俗易懂)
408考研——《数据结构》算法题基础篇之数组。(408算法题的入门)
72 23
基于GRU网络的MQAM调制信号检测算法matlab仿真,对比LSTM
本研究基于MATLAB 2022a,使用GRU网络对QAM调制信号进行检测。QAM是一种高效调制技术,广泛应用于现代通信系统。传统方法在复杂环境下性能下降,而GRU通过门控机制有效提取时间序列特征,实现16QAM、32QAM、64QAM、128QAM的准确检测。仿真结果显示,GRU在低SNR下表现优异,且训练速度快,参数少。核心程序包括模型预测、误检率和漏检率计算,并绘制准确率图。
83 65
基于GRU网络的MQAM调制信号检测算法matlab仿真,对比LSTM
基于PSO粒子群优化的CNN-LSTM-SAM网络时间序列回归预测算法matlab仿真
本项目展示了基于PSO优化的CNN-LSTM-SAM网络时间序列预测算法。使用Matlab2022a开发,完整代码含中文注释及操作视频。算法结合卷积层提取局部特征、LSTM处理长期依赖、自注意力机制捕捉全局特征,通过粒子群优化提升预测精度。适用于金融市场、气象预报等领域,提供高效准确的预测结果。
基于Big-Bang-Big-Crunch(BBBC)算法的目标函数最小值计算matlab仿真
该程序基于Big-Bang-Big-Crunch (BBBC)算法,在MATLAB2022A中实现目标函数最小值的计算与仿真。通过模拟宇宙大爆炸和大收缩过程,算法在解空间中搜索最优解。程序初始化随机解集,经过扩张和收缩阶段逐步逼近全局最优解,并记录每次迭代的最佳适应度。最终输出最佳解及其对应的目标函数最小值,并绘制收敛曲线展示优化过程。 核心代码实现了主循环、粒子位置更新、适应度评估及最优解更新等功能。程序运行后无水印,提供清晰的结果展示。
基于CS模型和CV模型的多目标协同滤波跟踪算法matlab仿真
本项目基于CS模型和CV模型的多目标协同滤波跟踪算法,旨在提高复杂场景下多个移动目标的跟踪精度和鲁棒性。通过融合目标间的关系和数据关联性,优化跟踪结果。程序在MATLAB2022A上运行,展示了真实轨迹与滤波轨迹的对比、位置及速度误差均值和均方误差等关键指标。核心代码包括对目标轨迹、速度及误差的详细绘图分析,验证了算法的有效性。该算法结合CS模型的初步聚类和CV模型的投票机制,增强了目标状态估计的准确性,尤其适用于遮挡、重叠和快速运动等复杂场景。
基于Adaboost的数据分类算法matlab仿真
本程序基于Adaboost算法进行数据分类的Matlab仿真,对比线性与非线性分类效果。使用MATLAB2022A版本运行,展示完整无水印结果。AdaBoost通过迭代训练弱分类器并赋予错分样本更高权重,最终组合成强分类器,显著提升预测准确率。随着弱分类器数量增加,训练误差逐渐减小。核心代码实现详细,适合研究和教学使用。
AI助理

你好,我是AI助理

可以解答问题、推荐解决方案等