From 01cef09ea895fd2fc7fb9cbdc76e4a04ed7c2955 Mon Sep 17 00:00:00 2001 From: TrsmYsk <53941356+TrsmYsk@users.noreply.github.com> Date: Mon, 29 Sep 2025 13:52:27 +0900 Subject: [PATCH] Create 83. Remove Duplicates from Sorted List.md --- .../83. Remove Duplicates from Sorted List.md | 52 +++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 83. Remove Duplicates from Sorted List/83. Remove Duplicates from Sorted List.md diff --git a/83. Remove Duplicates from Sorted List/83. Remove Duplicates from Sorted List.md b/83. Remove Duplicates from Sorted List/83. Remove Duplicates from Sorted List.md new file mode 100644 index 0000000..a9f85d3 --- /dev/null +++ b/83. Remove Duplicates from Sorted List/83. Remove Duplicates from Sorted List.md @@ -0,0 +1,52 @@ +問題文: https://leetcode.com/problems/remove-duplicates-from-sorted-list/description/ + +# step1: 何も見ないで書く +- 2重ループを使った方法で書いた。 + - 時間計算量O(n): ループがノード全体を走るから。 + - 空間計算量O(1): 何個ノードがあっても必要な変数は2つ。 +- 問題文に記載はなかったがノードの値はおそらくint型なので値の比較は == で行った。 +- 重複チェックの対象になるノードをforwardという変数に格納しようかとも思ったが、読みやすさは変わらなそうなのでやめた。 +```python +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]: + node = head + while node is not None: + while node.next is not None and node.val == node.next.val: + node.next = node.next.next + node = node.next + return head + +``` + +# step2: 他の人を参考にコードを整える +- 2重ループではなく、ループと if elseを組み合わせた方法もあったが、あまり直観的な方法ではない感じがしたので採用しなかった。 +```python +class Solution: + def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]: + node = head + while node is not None: + while node.next is not None and node.val == node.next.val: + node.next = node.next.next + node = node.next + return head + +``` + +# step3: 10分以内に3回ミスなく書く + +```python +class Solution: + def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]: + node = head + while node is not None: + while node.next is not None and node.next.val == node.val: + node.next = node.next.next + node = node.next + return head + +```