Conversation
| } | ||
| return dummyHead.next; | ||
| } | ||
| } |
There was a problem hiding this comment.
There was a problem hiding this comment.
なるほど、こちらは気づきませんでした。ありがとうございます。
| - 2 回目: 再度頭から走査。先頭が重複ノードだった場合に備え、重複していないノードまで進める | ||
| - 3 回目: 改めて新しい先頭から走査。HashSets を確認しながら値重複ノードはスキップしつつ、重複がないノード同士をつなげ直す | ||
| - 感想 | ||
| - なんとなくもっと見やすくて効率の良い方法がありそうなモヤモヤがありながらも、思いつかなかったので上記の発想で走りきったという感じ |
There was a problem hiding this comment.
このあたりにどう引き継ぐかどう考えるかを書いてあったと思います。
https://docs.google.com/document/d/11HV35ADPo9QxJOpJQ24FcZvtvioli770WWdZZDaLOfg/edit?tab=t.0
結局のところ、わりと、色々な方法があるんですが、どういう状態で引き継いだのか、なんですよね。
| - 3 つのポインタを使用 | ||
| - node: メインでリストを一つずつ走査するノード。head からスタート | ||
| - dummyHead: 番兵として元のリストの head の手前に配置する | ||
| - 番兵 を先頭に置くことで、本来の head 自体が削除対象となるケース(1->1->2 など)を考慮したループ処理が不要になる |
There was a problem hiding this comment.
実装してみました。やはりdummyHeadがあった方が書きやすいと思いました。
| ListNode node = head; | ||
| HashSet<Integer> duplicateVals = new HashSet<>(); | ||
|
|
||
| while (node != null && node.next != null) { |
There was a problem hiding this comment.
head はすでに null かどうかのチェックをしているため、
while (node.next != null) {
で十分だと思いました。
| node = head; | ||
| while (node != null && duplicateVals.contains(node.val)) { | ||
| if (node.next == null) { // All nodes are duplicated. | ||
| node = null; |
There was a problem hiding this comment.
ここですべてのノードの値が重複しているので、ここで return null; としてしまってよいと思いました。
| lastUnique.next = null; | ||
| } else { | ||
| lastUnique.next = node; | ||
| lastUnique = node; |
There was a problem hiding this comment.
lastUnique と lastUnique.next の両方に同じ node を代入している点に違和感を感じました。
lastUnique.next = node;
lastUnique = lastUnique.next;としたほうが、 lastUnique を進めている感じが出て、分かりやすくなると思います。
| ListNode dummyHead = new ListNode(0, head); | ||
| ListNode node = dummyHead; | ||
|
|
||
| while (node.next != null) { |
There was a problem hiding this comment.
node.next.next == null の場合に node = node.next; で node を進めたあと、 while (node.next != null) { でループを抜けようとしている点が、ややパズルに感じました。
自分なら
while (node.next != null && node.next.next != null) {
if (node.next.val != node.next.next.val) {と書くと思います。
There was a problem hiding this comment.
たしかにこちらの方が自然ですね。ありがとうございます。
問題
https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/
言語
Java
次に解く問題