iT邦幫忙

2022 iThome 鐵人賽

DAY 23
0
自我挑戰組

LeetCode Top 100 Liked系列 第 23

[Day 23] Remove Nth Node From End of List (Medium)

  • 分享至 

  • xImage
  •  

19. Remove Nth Node From End of List

Question

Given the head of a linked list, remove the nth node from the end of the list and return its head.

Example 1

Input: head = [1,2,3,4,5], n = 2
Output: [1,2,3,5]

Example 2

Input: head = [1], n = 1
Output: []

Example 3

Input: head = [1,2], n = 1
Output: [1]

Solution 1: Slow & Fast pointers + Dummy Head

class Solution:
    def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
        pSlow = pFast = dummy = ListNode(-1)
        dummy.next = head
        for _ in range(n):
            pFast = pFast.next

        while pFast.next:
            pFast = pFast.next
            pSlow = pSlow.next

        targetNode = pSlow.next
        pSlow.next = pSlow.next.next
        del targetNode        
        return dummy.next

Time Complexity: O(N)
Space Complexity: O(1)

Solution 2: Slow & Fast pointers

class Solution:
    def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
        ptrFast = head
        for _ in range(n):
            ptrFast = ptrFast.next

        # n == size of list
        if not ptrFast:
            return head.next
        
        ptrSlow = head
        while ptrFast.next:
            ptrFast = ptrFast.next
            ptrSlow = ptrSlow.next

        targetNode = ptrSlow.next
        ptrSlow.next = ptrSlow.next.next
        del targetNode        
        return head

Time Complexity: O(N)
Space Complexity: O(1)

Reference

https://leetcode.com/problems/remove-nth-node-from-end-of-list/discuss/8802/3-short-Python-solutions

Follow-up: Delete N Nodes After M Nodes of a Linked List

TODO

Time Complexity: O()
Space Complexity: O()


上一篇
[Day 22] LRU Cache (Medium)
下一篇
[Day 24] Search in Rotated Sorted Array (Medium)
系列文
LeetCode Top 100 Liked77
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言