Skip to content

82.remove duplicates from sorted list Ⅱ#4

Open
nicah4o wants to merge 1 commit into
mainfrom
82.remove-duplicates-from-sorted-listⅡ

Hidden character warning

The head ref may contain hidden characters: "82.remove-duplicates-from-sorted-list\u2161"
Open

82.remove duplicates from sorted list Ⅱ#4
nicah4o wants to merge 1 commit into
mainfrom
82.remove-duplicates-from-sorted-listⅡ

Conversation

@nicah4o
Copy link
Copy Markdown
Owner

@nicah4o nicah4o commented May 4, 2026

ListNode* deleteDuplicates(ListNode* head) {
if (head == nullptr || head->next == nullptr) {
return head;
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ここの早期リターンは無くても正常に動く気がします

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

そうですね、その後でもう一度同じ条件にかけていますね。
ポインタが多くなると把握しきれなくなってるので注意します。

class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
if (head==nullptr) {
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

演算子周辺の空白の取り方について何かしらのコーディング規約に則っておいた方がいいと思いました。
https://ttsuki.github.io/styleguide/cppguide.ja.html
これの水平方向の空白セクションなど参考になると思います。

}
unordered_set<int> seen;
ListNode *fore=head;
ListNode *back=head;
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

出現したvalをsetに入れて解く方法で解けると思いますが、それだと今回与えられたSorted Listという条件を活かせないと思います。ソートされてないリストが与えられてそこからduplicateがないリストにしてくださいとなるとsetで出現した値を入れて空間計算量O(n)になりますが、sorted listだとポインタの比較でO(1)にすることができます。

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

コメントありがとうございます。
なるほど、ソートされているという条件はポインタの連続的な処理に有利に働きますね。
計算量を考えるだけでなくどういう条件が影響しているのか考えるようにします。

return dummy.next;
}
};
```
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is_deletingdeleting を使って、「現在削除中の値」を状態として管理している点が分かりやすい実装だと思いました。
重複検出と削除処理を明確に分離しているので、処理の流れを追いやすかったです。
また、continue を使ってネストを浅く保っている点も読みやすいと感じました。

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

レビューありがとうございます。
このコードいいですよね。他の方のコードを真似たのですが、参考になります。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants