Skip to content

Latest commit

 

History

History
112 lines (81 loc) · 2.15 KB

README_EN.md

File metadata and controls

112 lines (81 loc) · 2.15 KB

中文文档

Description

Write code to remove duplicates from an unsorted linked list.

Example1:

 Input: [1, 2, 3, 3, 2, 1]

 Output: [1, 2, 3]

Example2:

 Input: [1, 1, 1, 1, 2]

 Output: [1, 2]

Note:

  1. The length of the list is within the range[0, 20000].
  2. <li>The values of the list elements are within the range [0, 20000].</li>
    

Follow Up:

How would you solve this problem if a temporary buffer is not allowed?

Solutions

Python3

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def removeDuplicateNodes(self, head: ListNode) -> ListNode:
        if head is None or head.next is None:
            return head
        cache = set()
        cache.add(head.val)
        cur, p = head, head.next
        while p:
            if p.val not in cache:
                cur.next = p
                cur = cur.next
                cache.add(p.val)
            p = p.next
        cur.next = None
        return head

Java

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode removeDuplicateNodes(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        Set<Integer> s = new HashSet<>();
        s.add(head.val);
        ListNode p = head.next, cur = head;
        while (p != null) {
            if (!s.contains(p.val)) {
                cur.next = p;
                cur = cur.next;
                s.add(p.val);
            }
            p = p.next;
        }
        cur.next = null;
        return head;

    }
}

...