中级农民
- 积分
- 118
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2016-11-5
- 最后登录
- 1970-1-1
|
Apr. 10th 2018 --- 3 Problems
## 138. Copy List With Random Pointer (Medium)
### 1. HashMap (O(N), O(N))
The most obvious solution is to use a HashMap to store the map between original node and duplicated node.
### 2. Scan and Modify the Original Linked List (O(N), O(1))
This approach is much more interested. In order to save space, we modify the original linked list instead.
When copy a node, insert it into the linked list just after its origin. `dup = iter.next, iter.next = dup;` In such a way, the odd nodes in the list are original and the even nodes are duplicates.
Next, complete the random pointers of the duplicates.
At last, extract new list and restore the origin list.
### Faults:
1. **[TLE]** You need go to `iter.next.next` when you add a new node after `iter`.
2. **[RE]** Forget to make a copy before some node is changed.
3. **[RE]** Same as above.
## 139. Word Break (Medium)
(S is the length of string s, W is the longest length of words, and N is the number of words.)
### 1. KMP + DP (O((S+W)\*N, O(S\*N))
This is my solution.
First use KMP to match each word and string s to calculate array m[k], which means whether the k-th word will match the substring end by position i in string s.
Then use DP to calculate f (wether the first i characters in string could be matched) by enumerate the words in the wordDict.
Array m[k] could be replaced by HashMap<String, HashSet>
### 2. HashSet + DP (O(S\*S), O(W\*N))
Instead of enumerate words during DP, this approach enumerate the length of substring to be matched. In such a way, you don't need to pretreat the strings by KMP, and you should put all the strings in a HashSet.
Which solution's performance is better depends on the distribute of the data.
### 3. DP (O(S\*S\*N), O(S))
This approach is even more violent. Don't use HashSet, just let the List provided by the system to do the searching.
## 140. Word Break II (Hard)
Memorized DFS.
### Faults:
1. **[WA]** Extra space in the output.
2. **[TLE]** Not enough optimization.
3. **[TLE]** Same as above.
|
|