1.查找最小的K个元素:利用容器来实现。如果容器中数的个数小于K时,直接插入新数。若容器存满K个数,找出K个数中最大值,当新的数据到来时,比较最大值和新数之间的大小,当新数小于最大值时,删除最大主,并且插入新数。若新数大于最大值,则抛弃新数,直接进行下一个新数的比较。
容器中K个数要找出最大值,用二叉树中的最大堆可以实现。实际中,用红黑树实现容器比较简单。红黑树通过把结点分为红、黑两种颜色并根据一些规则确保树是平衡的,从而保证在红黑树中查找、删除和插入操作都只需要O(logk)。在STL中set和multiset都是基于红黑树实现的。
void FindKLeastNumbers
(
const vector<int>& data, // a vector of data
IntHeap& leastNumbers, // k least numbers, output
unsigned int k
)
{
leastNumbers.clear();
if(k == 0 || data.size() < k)
return;
vector<int>::const_iterator iter = data.begin();
for(; iter != data.end(); ++ iter)
{
// if less than k numbers was inserted into leastNumbers
if((leastNumbers.size()) < k)
leastNumbers.insert(*iter);
// leastNumbers contains k numbers and it's full now
else
{
// first number in leastNumbers is the greatest one
IntHeap::iterator iterFirst = leastNumbers.begin();
// if is less than the previous greatest number
if(*iter < *(leastNumbers.begin()))
{
// replace the previous greatest number
leastNumbers.erase(iterFirst);
leastNumbers.insert(*iter);
}
}
}
}
2.两个栈实现1个队列
template<typename T> class CQueue
{
public:
CQueue(){};
~CQueue(){};
void appendTail(const &node);
void deleteHead();
private:
T->m_stack1;
T->m_statck2;
};
template<typename T> void CQueue<T>::appendTail(const T&element)
{
m_statck1.push(element);
}
template<typename T> void CQueue<T>::deleteHead()
{
if(m_statck2.size<=0)
{
while(m_stack1.size()>0)
{
T &data=m_stack1.pop();
m_stack1.pop();
m_stack.pusj(data);
}
}
assert(m_stack2.size()>0)
m_stack2.pop;
}
3.从尾到投输出链表的节点