83.删除排序链表中的重复元素
链接:83.删除排序链表中的重复元素
难度:Easy
标签:链表
简介:给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。
题解 1 - typescript
- 编辑时间:2021-03-26
- 执行用时:96ms
- 内存消耗:39.9MB
- 编程语言:typescript
- 解法介绍:依次判断是否与下一个值相等。
function deleteDuplicates(head: ListNode | null): ListNode | null {
  if (head === null) return null;
  let p: ListNode | null = head;
  while (p !== null) {
    while (p.next !== null && p.val === p.next.val) p.next = p.next.next;
    p = p.next;
  }
  return head;
}
题解 2 - typescript
- 编辑时间:2021-03-06
- 执行用时:100ms
- 内存消耗:40MB
- 编程语言:typescript
- 解法介绍:利用已排序的特点直接进行比较。
function deleteDuplicates(head: ListNode | null): ListNode | null {
  if (head === null) return null;
  let p = head;
  while (p.next !== null)
    if (p.val === p.next.val) p.next = p.next.next;
    else p = p.next;
  return head;
}
题解 3 - c
- 编辑时间:2021-11-19
- 执行用时:4ms
- 内存消耗:6.2MB
- 编程语言:c
- 解法介绍:双指针。
struct ListNode* deleteDuplicates(struct ListNode* head){
    struct ListNode *p = head;
    struct ListNode *work_p = head;
    while (work_p) {
        while (work_p && work_p->val == p->val) work_p = work_p->next;
        p->next = work_p;
        p = p->next;
    }
    return head;
}
题解 4 - java
- 编辑时间:2020-02-13
- 执行用时:3ms
- 内存消耗:45MB
- 编程语言:java
- 解法介绍:使用 set 储存元素,储存前会先判断 set 中是否已存在,若存在则移除。
class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        if(head==null) {
			return null;
		}
		HashSet<Integer> set = new HashSet<Integer>();
		ListNode newHead=head;
		set.add(head.val);
		while(head.next!=null) {
			if(!set.contains(head.next.val)) {
				set.add(head.next.val);
				head=head.next;
			}else {
				head.next=head.next.next;
			}
		}
        return newHead;
    }
}