左神算法笔记: 3. 比较器与堆

algorithem/左神算法/基础

  1. 完全二叉树
    • 一种想象的数据结构
    • 实际是组数:
      1. 使用0节点
        • 左子节点:2i + 1
        • 右子节点:2i + 2
        • 父节点:( i - 1 ) / 2
      2. 不使用0节点
        • 左子节点:2i
        • 右子节点:2i + 1
        • 父节点:i / 2
  2. 堆排序 ::堆排序的额外空间复杂度为O(1)::
    1. 先让整个数组都变成大根堆结构,建立堆的过程:
      1. 从上到下的方法(生成heap),时间复杂度为O(N*logN)

        1. 把堆的最大值(root)和堆末尾的值交换,然后减少堆的大小,做一个heapify操作,再一直周而复始,时间复杂度为O(N*logN)
        2. 堆的大小减成0之后,排序完成
      2. 从下到上的方法(生成heap),时间复杂度为O(N)[image:4E5AA9A4-CF04-4821-848E-65A16FBD196C-6764-0001850E42CD133E/59D6BF48-9953-4AF6-B979-9D984B8EF721.png][image:8A018553-1C68-4B33-9A31-D203B6B6518B-6764-0001850517DDC2C8/356F41D8-FF55-4ED1-86FD-E4708A1FC823.png]

      3. 堆的大小减为0时,排序完成


    // 堆排序额外空间复杂度O(1)
    public static void heapSort(int[] arr) {
        if (arr == null || arr.length < 2) {
            return;
        }
        // O(N*logN)
        for (int i = 0; i < arr.length; i++) { // O(N)
            heapInsert(arr, i); // O(logN)
        }
        // O(N)
        // for (int i = arr.length - 1; i >= 0; i--) {
        // heapify(arr, i, arr.length);
        // }
        int heapSize = arr.length;
        swap(arr, 0, --heapSize);
        // O(N*logN)
        while (heapSize > 0) { // O(N)
            heapify(arr, 0, heapSize); // O(logN)
            swap(arr, 0, --heapSize); // O(1)
        }
    }

    // arr[index]刚来的数,往上
    public static void heapInsert(int[] arr, int index) {
        while (arr[index] > arr[(index - 1) / 2]) {
            swap(arr, index, (index - 1) / 2);
            index = (index - 1) / 2;
        }
    }

    // arr[index]位置的数,能否往下移动
    public static void heapify(int[] arr, int index, int heapSize) {
        int left = index * 2 + 1; // 左孩子的下标
        while (left < heapSize) { // 下方还有孩子的时候
            // 两个孩子中,谁的值大,把下标给largest
            // 1)只有左孩子,left -> largest
            // 2) 同时有左孩子和右孩子,右孩子的值<= 左孩子的值,left -> largest
            // 3) 同时有左孩子和右孩子并且右孩子的值> 左孩子的值, right -> largest
            int largest = left + 1 < heapSize && arr[left + 1] > arr[left] ? left + 1 : left;
            // 父和较大的孩子之间,谁的值大,把下标给largest
            largest = arr[largest] > arr[index] ? largest : index;
            if (largest == index) {
                break;
            }
            swap(arr, largest, index);
            index = largest;
            left = index * 2 + 1;
        }
    }



  • 比较器
    1. 比较器的实质就是重载比较运算符
    2. 比较器可以很好的应用在特殊标准的排序上
    3. 比较器可以很好的应用在特殊标准排序的结构上[image:47A6D0E7-F190-499B-B99C-09A939BD3150-6764-00018AC3B67A7A2B/iShot2020-12-11 01.59.22.png]
    4. 写代码变得异常容易,还用于范型编程
    5. 需求:用户更改了某个值(影响排序),如何维持堆结构
      [image:B9823442-80A9-41A8-BC99-53101E2ECCAC-6764-00018ADA07DA0770/9AFE6CBA-D86F-4D81-8CFE-89B911E4DE29.png]
  • 实现:HashMap<T, Integer> indexMap 结构用来记录每个节点所在的位置,然后就可以通过对获得的Index进行一个向上冒泡的排序heapInsert(),和一个向下冒泡的排序heapify() ::两者实际只会执行一个::
/*
 * T一定要是非基础类型,有基础类型需求包一层
 */
public class HeapGreater<T> {

	private ArrayList<T> heap;
	private HashMap<T, Integer> indexMap;
	private int heapSize;
	private Comparator<? super T> comp;

	public HeapGreater(Comparator<T> c) {
		heap = new ArrayList<>();
		indexMap = new HashMap<>();
		heapSize = 0;
		comp = c;
	}

	public boolean isEmpty() {
		return heapSize == 0;
	}

	public int size() {
		return heapSize;
	}

	public boolean contains(T obj) {
		return indexMap.containsKey(obj);
	}

	public T peek() {
		return heap.get(0);
	}

	public void push(T obj) {
		heap.add(obj);
		indexMap.put(obj, heapSize);
		heapInsert(heapSize++);
	}

	public T pop() {
		T ans = heap.get(0);
		swap(0, heapSize - 1);
		indexMap.remove(ans);
		heap.remove(--heapSize);
		heapify(0);
		return ans;
	}

	public void remove(T obj) {
		T replace = heap.get(heapSize - 1);
		int index = indexMap.get(obj);
		indexMap.remove(obj);
		heap.remove(--heapSize);
		if (obj != replace) {
			heap.set(index, replace);
			indexMap.put(replace, index);
			resign(replace);
		}
	}

	public void resign(T obj) {
		heapInsert(indexMap.get(obj));
		heapify(indexMap.get(obj));
	}

	// 请返回堆上的所有元素
	public List<T> getAllElements() {
		List<T> ans = new ArrayList<>();
		for (T c : heap) {
			ans.add(c);
		}
		return ans;
	}

	private void heapInsert(int index) {
		while (comp.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 left = index * 2 + 1;
		while (left < heapSize) {
			int best = left + 1 < heapSize && comp.compare(heap.get(left + 1), heap.get(left)) < 0 ? (left + 1) : left;
			best = comp.compare(heap.get(best), heap.get(index)) < 0 ? best : index;
			if (best == index) {
				break;
			}
			swap(best, index);
			index = best;
			left = index * 2 + 1;
		}
	}

	private void swap(int i, int j) {
		T o1 = heap.get(i);
		T o2 = heap.get(j);
		heap.set(i, o2);
		heap.set(j, o1);
		indexMap.put(o2, i);
		indexMap.put(o1, j);
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值