zoukankan      html  css  js  c++  java
  • 【数据结构】堆的删除

    题目

    实现在最小堆中删除给定序号为pos的元素,并由x返回,删除成功返回true,失败返回false。(注意:删除后要保持数据结构是最小堆。)

    算法实现

    在最小堆中删除给定序号为pos的元素,我们可以先删除该元素后将堆中最后一个元素补到该位子,然后向下调整为堆,在从该位置向上调整为堆。
    1 如果堆空返回false
    2 x = heap[pos]; // 返回元素
    3 heap[pos] = heap[currentSize - 1]; //最后元素填补到pos结点
    4 currentSize--;
    5 siftDown(pos, currentSize - 1);//自上向下调整为堆
    6 siftUp(pos); //向上调整为堆
    时间复杂度为O(logn)

    代码

    template <class E>bool MinHeap <E>::Remove(int &pos,E &x) 
    {
    	if (!currentSize) {	//堆空, 返回false	
    		cout << "Heap empty" << endl;
    		return false;
    	}
    	x = heap[pos];		// 返回该元素
    	heap[pos] = heap[currentSize - 1];	//最后元素填补到pos结点
    	currentSize--;
    	siftDown(pos, currentSize - 1);//自上向下调整为堆
    	siftUp(pos);
    	return true;
    }
    
  • 相关阅读:
    HackerRank
    HackerRank
    LeetCode "Kth Smallest Element in a BST"
    HackerRank
    HackerRank
    LeetCode "Roman to Integer"
    LeetCode "Integer to Roman"
    LeetCode "Majority Element II"
    HackerRank
    HackerRank
  • 原文地址:https://www.cnblogs.com/muyefeiwu/p/11838600.html
Copyright © 2011-2022 走看看