LeetCode 面试题 02.01. 移除重复节点

题目描述

🔥 面试题 02.01. 移除重复节点

image-20230305203836056

思路分析

哈希表

参考代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
func removeDuplicateNodes(head *ListNode) *ListNode {
	if head == nil || head.Next == nil {
		return head
	}
	visited := make(map[int]bool)
	var pre *ListNode
	cur := head
	for cur != nil {
		if _, ok := visited[cur.Val]; ok {
			pre.Next = cur.Next
		} else {
			visited[cur.Val] = true
			pre = cur
		}
		cur = cur.Next
	}
	return head
}

🍏 点击查看 Java 题解

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
    public ListNode removeDuplicateNodes(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode pre = null, cur = head;
        Set<Integer> visited = new HashSet<>();
        while (cur != null) {
            if (visited.contains(cur.val)) {
                pre.next = cur.next;
            } else {
                visited.add(cur.val);
                pre = cur;
            }
            cur = cur.next;
        }
        return head;
    }
}
本文作者:
本文链接: https://hgnulb.github.io/blog/2023/11916133
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处!