中级农民
- 积分
- 278
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2011-2-2
- 最后登录
- 1970-1-1
|
https://github.com/writecoffee/c ... blob/master/9.2.cpp
1. Solution 1: Sacrifice the Space
• For each string, record the appearence of the 26 letters and make pair. Do a quick sort.
• The record work is proportional to the size of each strings, namely O(m). And the compar-
ison for the record sets take constant time (thinking the maximum size of these 26 letters).
At last, the quick sort which takes O(n log n) timing dominates the total timing complexity.
• As for the space complexity, extra mapping set for each string consumes O(n).
2. Solution 2: Sacrifice the Timing
• Sort the string list in place, where we need to copy the strings, compare the anagrams every
time comparing each list item.
• For the sake of each comparison inside the outer quick sort loop, the total time complexity
is O(mn log n).
• Because we exploit temporary space for each comparison, the space complexity could be
considered O(1).
========PS===========
1. hard to modify a quicksort to a version which can sort with equivalent values.
2. overloading the comparator in C++ is a bit tricky for me. |
|