因此,当我在处理编程竞赛(ACM ICPC等)中的一些实践问题时,人们经常可以采用O(N^2)解决方案,甚至更糟,并使用堆(C++中的priority_queue)或use来降低复杂性。(作为某种优化,在注意到模式中的“某些东西”之后)
例如,在“滑动窗口最大值”问题中,这几乎是:
For each window of size K in an array of size N, compute the maximum.
这里有一个简单的O(NK)算法,一个相当简单的O(nlogn)解决方案(甚至我都可以看到,使用一个堆)和一个O(N)解决方案,使用一个双端队列。
这些原则似乎是基于“丢弃”无用
在“算法设计手册”中找到了这个问题,问题的解决方案是
Sort2()
initialize-tree(t)
While (not EOF)
read(x);
insert(x,t);
y = Minimum(t)
While (y != NULL) do
print(y → item)
y = Successor(y,t)
它被解释为“第二个问题允许我们在构造树之后使用最小操作和后继操作,我们可以从最小元素开始,然后重复查找后续元素,按照排序顺序遍历元素。”
我想我不是在跟踪Sort2()。如果y被初始化为最小节点,那么它不可能没有任何后续节点吗
我正试着解决这个密码问题。我实现了一个MaxHeap,并尝试弹出值以获得数组中最大的Kth元素,但我得到了超过时间限制的结果。
我的MaxHeap实现有什么问题吗?它是慢的,还是可以用更快的方法完成?
问题
class Solution {
private int capacity = 10;
private int size = 0;
int items [] = new int[capacity];
//parent = (i-1)/2
//left-child = 2i+1
//right-child = 2i
public int findKthLargest(int[] n
# To heapify subtree rooted at index i.
def maxHeapify(list, heapSize, i):
largest = i
leftChild = 2 * i
rightChild = 2 * i + 1
while leftChild < heapSize and list[largest] < list[leftChild]:
largest = leftChild
while rightChild < heapSize and list[largest] <