LeetCode 面试题 02.01. 移除重复节点
题目描述
思路分析
哈希表
参考代码
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
}
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
许可协议,转载请注明出处!
本博客所有文章除特别声明外,均采用