LeetCode 面试题 02.01. 移除重复节点
题目描述
思路分析
哈希表
参考代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
func removeDuplicateNodes(head *ListNode) *ListNode {
if head == nil || head.Next == nil {
return head
}
seem := make(map[int]bool)
dummy := &ListNode{Next: head}
pre := dummy
cur := head
for cur != nil {
if seem[cur.Val] {
pre.Next = cur.Next
} else {
pre = cur
}
seem[cur.Val] = true
cur = cur.Next
}
return dummy.Next
}
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;
}
}
CC BY-NC-SA 4.0
许可协议,转载请注明出处!
本博客所有文章除特别声明外,均采用