插入新项目时保持Max Heap Sort

时间:2017-01-21 13:42:56

标签: arrays algorithm sorting math tree

我有建立银行系统的功课,同时以最有效的方式实施所有任务。

该计划可以:

1.add a new customer
2.delete an existing customer 
3.find a customer 
4.print the customer with the highest balance.
5.print all customers with a negative balance.
6.deposit/withdraw money 

我决定为前3个(O(log-n))选择Red-Black树。 我不确定第4和第5个。

4:我考虑过维持一个最大堆,以便获得最富有的'客户只需花费O(1) - 根节点。 我的最大堆代码适用于我试过的randoms数组(列表)。但是,在这个特定情况下,我显然从一个空数组开始,必须在以后填充。 当我在最大堆中使用insert方法时,会产生未排序的数组。 (因为我基本上跳过堆构建..)。 最大堆的插入方法:

dataArray.add( newCustomer );
heapSize = dataArray.size();
int i = dataArray.size()-1;
while( i > 1 && dataArray.get( getParentIndex(i) ).getAccountBalance() < newCustomer.getAccountBalance() )
{
     swap( dataArray, getParentIndex( i ) , i );
     i = getParentIndex(i);
}

5:我想过有一个负余额的链表。 这样,打印时复杂性将是线性的。 (即使没有负余额的客户也没有RBTree会花费logN)。 但是,如果我删除了一个客户,我将不得不搜索(O(n))该列表中的客户以删除他,然后删除功能将是( RBTree delete lgn + n 列表删除 = n * lgn)

2 个答案:

答案 0 :(得分:0)

我会维护两个二元搜索树(密钥将是唯一的客户ID),一个用于负余额的客户和一个用于正余额的客户。并且指针richest始终指向具有最高余额的客户。

在每次余额变更中,您应检查余额的符号是否发生变化。如果是这样,请从一棵树中删除客户并将其添加到另一棵树。

并根据余额richest检查当前余额,如果余额较高,则指定当前客户。

复杂性将是:

1. insert to tree: O(log(n))
2. delete from tree: O(log(n))
3. binary search in two trees: O(log(n))
4. print the customer pointed by `richest`: O(1)
5. in-order run on a binary search tree (the negative one): O(n)
6. find costumer: O(log(n)) + possible deletions and insertions: still O(log(n))

答案 1 :(得分:0)

只需添加@Nimrod Morag的解决方案,为了更好地averageamortized时间复杂,您可以使用Fibonacci-heap数据结构(参考{{3} }和https://en.wikipedia.org/wiki/Fibonacci_heap)并为客户(具有fib-max-heap指针)保留一个max,您可以执行所有操作:

1. insert (lazily) a customer to the heap: O(1) 
2. delete any customer (or the customer with maximum balance) 
   from heap: O(log(n)) amortized
3. search a customer in heap: O(log(n))
4. print the customer pointed by `max` pointer: O(1)
5. in-order run on the heap and print only the -ve balances: O(n)
6. deposit/withdraw money: O(1) amortized
相关问题