Python、C++、JavaScript、SQL、TypeScript の多様な LeetCode ソリューションを探索してください。面接の準備、学習、複数のプログラミング言語でのコードの練習に最適です。 Github リポジトリ リンク
目次
トグルパイソン
# 時間計算量: O(n) # 空間計算量: 入力による O(1) import オプションのクラス ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class 解決策: def deleteNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]: total = 0 countNode = resNode = head while countNode: total += 1 countNode = countNode.next delIdx = total - n - 1 if delIdx < 0: head = head.next return head currentIdx = 0 while resNode: if currentIdx == delIdx: if resNode.next.next: resNode.next = resNode.next.next else: resNode.next = None return head else : resNode = resNode.next currentIdx += 1 return head root = ListNode(1) root.next = ListNode(2) root.next.next = ListNode(3) root.next.next.next = ListNode(4) ルート。 next.next.next.next = ListNode(5) print(Solution().removeNthFromEnd(root, 2))