Conversation
| current = head | ||
|
|
||
| while current: | ||
| while current.next and current.val == current.next.val: |
There was a problem hiding this comment.
実際はO(n)でできているのですが、whileが二重になっているのでぱっと見O(n^2)になっていることがなんとなく気になります。二重whileを使わない方法としては、duplicatedなどのフラグを用意してやるとできると思います。
| ```python | ||
| class Solution: | ||
| def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]: | ||
| dummy = ListNode(0) |
There was a problem hiding this comment.
sentinel という単語を使うのも良いと思います。
hroc135/leetcode#4 (comment)
| while current_node: | ||
| while current_node.next and current_node.val == current_node.next.val: | ||
| current_node = current_node.next | ||
| if previous_node.next == current_node: |
There was a problem hiding this comment.
if 文の条件が True のときと False のときのどちらの時に値が重複しているのか、直感的でないように感じました。また、変数を previous_node と current_node の 2 つ使うのではなく、 1 つだけにしたほうがシンプルだと感じました。以下のようなコードはいかがでしょうか?
node = dummy
while node and node.next and node.next.next:
if node.next.val != node.next.next.val:
# 重複していない場合
# early return する。
node = node.next
continue
# 重複している場合
value = node.next.val
while node.next and node.next.val == value:
node.next = node.next.nextThere was a problem hiding this comment.
たしかにご提示のコードのほうが直感的だなと感じました。
| previous = dummy | ||
| current = head | ||
|
|
||
| while current: |
There was a problem hiding this comment.
currentの初期化時にcurrent = previous = dummyとしておくと、walrus演算子を使ってcurrent := current.nextと書くことができ、ループ変数を進める処理をわかりやすくできます(python3.8以降)
好みもありますが参考まで。
There was a problem hiding this comment.
walrus演算子で変数への代入と変数の使用を同時に行えるのですね。適切に使えるとコードをすっきりできそうだなと思いました。ありがとうございます。
| while current: | ||
| while current.next and current.val == current.next.val: | ||
| current = current.next | ||
| if previous.next == current: |
There was a problem hiding this comment.
Step1の指摘と類似ですが、ここの分岐は読み飛ばしが発生したかしていないかなので、もう少しわかりやすくできると嬉しいですね。前のwhileの条件と逆になるのが見にくいのかも?と思いました。
代入回数が増えてしまいますが、elseを省略することはできます。
while current.next and current.val == current.next.val:
current = current.next
previous.next = current.next
if previous.next == current:
previous = previous.nextThere was a problem hiding this comment.
ブロックがすくないこちらのほうが私も見やすいと感じました。
| current= current.next | ||
| return dummy.next | ||
| ``` | ||
| - 他の解き方がないかを考える。←再帰とか? |
There was a problem hiding this comment.
最適解ではありませんが、自分はHashMapでカウントしていく解法でも解きました。
Mike0121/LeetCode@5e139d5
問題:https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/
考えたこと:https://github.com/ask-1407/leetcode/blob/remove_duplicates_from_sorted_list_ii/Arai60/LinkedList/answer.md
次に解く予定:https://leetcode.com/problems/add-two-numbers/