////void FindPath BinaryTreeNode pTreeNode // a node of binary tree int expectedSum // the expected sum std::vectorltintgtamppath // a pathfrom root to current node intamp currentSum // the sum of path ifpTreeNode return currentSum pTreeNode-gtm_nValue path.push_backpTreeNode-gtm_nValue // if the node is a leaf and the sum is same as pre-defined // the path is what we want. print the path bool isLeaf pTreeNode-gtm_pLeft ampamp pTreeNode-gtm_pRight ifcurrentSum expectedSum ampamp isLeaf std::vectorltintgt::iterator iter path.beginfor iter path.end iter std::coutltltiterltltt std::coutltltstd::endl // if the node is not a leaf goto its children ifpTreeNode-gtm_pLeft FindPathpTreeNode-gtm_pLeft expectedSum path currentSum ifpTreeNode-gtm_pRight FindPathpTreeNode-gtm_pRight expectedSum path currentSum // when we finish visiting a node and return to its parent node // we should delete this node from the path and // minus the nodes value from the current sum currentSum - pTreeNode-gtm_nValue //I think here is no use path.pop_back05查找最小的 k 个元素题目:输入 n 个整数,输出其中最小的 k 个。
例如输入 1,2,3,4,5,6,7 和 8 这 8 个数字,则最小的 4 个数字为 1,2,3 和 4。
分析:这道题最简单的思路莫过于把输入的 n 个整数排序,这样排在最前面的 k 个数就是最小的 k 个数。
只是这种思路的时间复杂度为 Onlogn。
我们试着寻找更快的解决思路。
我们可以开辟一个长度为 k 的数组。
每次从输入的 n 个整数中读入一个数。
如果数组中已经插入的元素少于 k 个,则将读入的整数直接放到数组中。
否则长度为 k 的数组已经满了,不能再往数组里插入元素,只能替换了。
如果读入的这个整数比数组中已有 k 个整数的最大值要小,则用读入的这个整数替换这个最大值;如果读入的整数比数组中已有 k 个整数的最大值还要大,则读入的这个整数不可能是最小的 k 个整数之一,抛弃这个整数。
这种思路相当于只要排序 k 个整数,因此时间复杂可以降到 Onnlogk。
通常情况下 k 要远小于 n,所以这种办法要优于前面的思路。
这是我能够想出来的最快的解决方案。
不过从给面试官留下更好印象的角度出发,我们可以进一步把代码写得更漂亮一些。
从上面的分析,当长度为 k 的数组已经满了之后,如果需要替换,每次替换的都是数组中的最大值。
在常用的数据结构中,能够在 O1时间里得到最大值的数据结构为最大堆。
因此我们可以用堆(heap)来代替数组。
另外,自己重头开始写一个最大堆需要一定量的代码。
我们现在不需要重新去发明车轮,因为前人早就发明出来了。
同样,STL 中的 set 和 multiset 为我们做了很好的堆的实现,我们可以拿过来用。
既偷了懒,又给面试官留下熟悉 STL 的好印象,何乐而不为之?参考代码:include ltsetgtinclude ltvectorgtinclude ltiostreamgtusing namespace stdtypedef multisetltint greaterltintgt gt IntHeap//////////////////////////////.
上一篇:
基于PHP的教学网站
下一篇:
扛起年轻化大旗,哈弗F系玩转行业新风潮