19. Remove Nth Node From End of List

Leetcode

https://leetcode.com/problems/remove-nth-node-from-end-of-list/arrow-up-right

題目

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]

解答

  • 方法一

hashmap

Runtime: 139 ms, faster than 6.81% of JavaScript online submissions for Remove Nth Node From End of List.

Memory Usage: 39.4 MB, less than 98.63% of JavaScript online submissions for Remove Nth Node From End of List.

  • 方法二

Two pass algorithm

Runtime: 80 ms, faster than 67.89% of JavaScript online submissions for Remove Nth Node From End of List.

Memory Usage: 40.1 MB, less than 72.75% of JavaScript online submissions for Remove Nth Node From End of List.

  • 方法三

One pass algorithm

firstNode 先往前走,等到 firstNode 走到 n 的位置,secondNode 再跟 firstNode 一起走,等到 firstNode 走到底時,secondNode 即是我們要找的位置

Runtime: 97 ms, faster than 30.13% of JavaScript online submissions for Remove Nth Node From End of List.

Memory Usage: 39.8 MB, less than 86.38% of JavaScript online submissions for Remove Nth Node From End of List.

Last updated