返回介绍

solution / 0000-0099 / 0082.Remove Duplicates from Sorted List II / README_EN

发布于 2024-06-17 01:04:39 字数 8287 浏览 0 评论 0 收藏 0

82. Remove Duplicates from Sorted List II

中文文档

Description

Given the head of a sorted linked list, _delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list_. Return _the linked list sorted as well_.

 

Example 1:

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

Example 2:

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

 

Constraints:

  • The number of nodes in the list is in the range [0, 300].
  • -100 <= Node.val <= 100
  • The list is guaranteed to be sorted in ascending order.

Solutions

Solution 1: Single Pass

First, we create a dummy head node $dummy$, and set $dummy.next = head$. Then we create a pointer $pre$ pointing to $dummy$, and a pointer $cur$ pointing to $head$, and start traversing the linked list.

When the node value pointed by $cur$ is the same as the node value pointed by $cur.next$, we let $cur$ keep moving forward until the node value pointed by $cur$ is different from the node value pointed by $cur.next$. At this point, we check whether $pre.next$ is equal to $cur$. If they are equal, it means there are no duplicate nodes between $pre$ and $cur$, so we move $pre$ to the position of $cur$; otherwise, it means there are duplicate nodes between $pre$ and $cur$, so we set $pre.next$ to $cur.next$. Then we continue to move $cur$ forward. Continue the above operation until $cur$ is null, and the traversal ends.

Finally, return $dummy.next$.

The time complexity is $O(n)$, and the space complexity is $O(1)$. Here, $n$ is the length of the linked list.

# 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]:
    dummy = pre = ListNode(next=head)
    cur = head
    while cur:
      while cur.next and cur.next.val == cur.val:
        cur = cur.next
      if pre.next == cur:
        pre = cur
      else:
        pre.next = cur.next
      cur = cur.next
    return dummy.next
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *   int val;
 *   ListNode next;
 *   ListNode() {}
 *   ListNode(int val) { this.val = val; }
 *   ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
  public ListNode deleteDuplicates(ListNode head) {
    ListNode dummy = new ListNode(0, head);
    ListNode pre = dummy;
    ListNode cur = head;
    while (cur != null) {
      while (cur.next != null && cur.next.val == cur.val) {
        cur = cur.next;
      }
      if (pre.next == cur) {
        pre = cur;
      } else {
        pre.next = cur.next;
      }
      cur = cur.next;
    }
    return dummy.next;
  }
}
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *   int val;
 *   ListNode *next;
 *   ListNode() : val(0), next(nullptr) {}
 *   ListNode(int x) : val(x), next(nullptr) {}
 *   ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
  ListNode* deleteDuplicates(ListNode* head) {
    ListNode* dummy = new ListNode(0, head);
    ListNode* pre = dummy;
    ListNode* cur = head;
    while (cur) {
      while (cur->next && cur->next->val == cur->val) {
        cur = cur->next;
      }
      if (pre->next == cur) {
        pre = cur;
      } else {
        pre->next = cur->next;
      }
      cur = cur->next;
    }
    return dummy->next;
  }
};
/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *   Val int
 *   Next *ListNode
 * }
 */
func deleteDuplicates(head *ListNode) *ListNode {
  dummy := &ListNode{Next: head}
  pre, cur := dummy, head
  for cur != nil {
    for cur.Next != nil && cur.Next.Val == cur.Val {
      cur = cur.Next
    }
    if pre.Next == cur {
      pre = cur
    } else {
      pre.Next = cur.Next
    }
    cur = cur.Next
  }
  return dummy.Next
}
/**
 * Definition for singly-linked list.
 * class ListNode {
 *   val: number
 *   next: ListNode | null
 *   constructor(val?: number, next?: ListNode | null) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 *   }
 * }
 */

function deleteDuplicates(head: ListNode | null): ListNode | null {
  const dummy = new ListNode(0, head);
  let pre = dummy;
  let cur = head;
  while (cur) {
    while (cur.next && cur.val === cur.next.val) {
      cur = cur.next;
    }
    if (pre.next === cur) {
      pre = cur;
    } else {
      pre.next = cur.next;
    }
    cur = cur.next;
  }
  return dummy.next;
}
// Definition for singly-linked list.
// #[derive(PartialEq, Eq, Clone, Debug)]
// pub struct ListNode {
//   pub val: i32,
//   pub next: Option<Box<ListNode>>
// }
//
// impl ListNode {
//   #[inline]
//   fn new(val: i32) -> Self {
//   ListNode {
//     next: None,
//     val
//   }
//   }
// }
impl Solution {
  pub fn delete_duplicates(mut head: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
    let mut dummy = Some(Box::new(ListNode::new(101)));
    let mut pev = dummy.as_mut().unwrap();
    let mut cur = head;
    let mut pre = 101;
    while let Some(mut node) = cur {
      cur = node.next.take();
      if node.val == pre || (cur.is_some() && cur.as_ref().unwrap().val == node.val) {
        pre = node.val;
      } else {
        pre = node.val;
        pev.next = Some(node);
        pev = pev.next.as_mut().unwrap();
      }
    }
    dummy.unwrap().next
  }
}
/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *   this.val = (val===undefined ? 0 : val)
 *   this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @return {ListNode}
 */
var deleteDuplicates = function (head) {
  const dummy = new ListNode(0, head);
  let pre = dummy;
  let cur = head;
  while (cur) {
    while (cur.next && cur.val === cur.next.val) {
      cur = cur.next;
    }
    if (pre.next === cur) {
      pre = cur;
    } else {
      pre.next = cur.next;
    }
    cur = cur.next;
  }
  return dummy.next;
};
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *   public int val;
 *   public ListNode next;
 *   public ListNode(int val=0, ListNode next=null) {
 *     this.val = val;
 *     this.next = next;
 *   }
 * }
 */
public class Solution {
  public ListNode DeleteDuplicates(ListNode head) {
    ListNode dummy = new ListNode(0, head);
    ListNode pre = dummy;
    ListNode cur = head;
    while (cur != null) {
      while (cur.next != null && cur.next.val == cur.val) {
        cur = cur.next;
      }
      if (pre.next == cur) {
        pre = cur;
      } else {
        pre.next = cur.next;
      }
      cur = cur.next;
    }
    return dummy.next;
  }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文