题目
思路
用一个Set集合保存每个节点的值,使用一前一后双指针,如果后指针遍历到的节点值出现过,则说明该节点为重复节点,则修改前指针的next指针的对象指向,删除重复节点。如果后指针遍历到的节点值没有出现在Set中,则前后指针都往后移动即可。
代码实现(Java)
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode removeDuplicateNodes(ListNode head) {
if(head == null){
return head;
}
Set<Integer> set = new HashSet<Integer>();
ListNode res = head;
ListNode next = head.next;
set.add(head.val);
while(next != null) {
if(set.contains(next.val)){
head.next = next.next;
} else {
set.add(next.val);
head = head.next;
}
next = head.next;
}
return res;
}
}
深度思考
我用了HashMap 和 HashSet 都实现了一遍,对比时间效率,发现 HashMap 的时间消耗更大,如下图
HashMap实现
HashMap对应的实现代码
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode removeDuplicateNodes(ListNode head) {
if(head == null){
return head;
}
HashMap<Integer,Integer> set = new HashMap<Integer,Integer>();
ListNode res = head;
ListNode next = head.next;
set.put(head.val,head.val);
while(next != null) {
if(set.containsValue(next.val)){
head.next = next.next;
} else {
set.put(next.val,next.val);
head = head.next;
}
next = head.next;
}
return res;
}
}
HashSet实现
思考
HashSet 的底层是用HashMap实现的,查看 contains 的源码发现
我用HashMap实现的时候,使用的是 HashMap 的 containsValue 实现,所以时间复杂度更高,将 containsValue 改为 containsKey 实现后,效率就和HashSet 一样高了。
总结
在利用 HashMap 判重的时候,尽量使用 containsKey 实现,这样子复杂度会更低。然后要多看源码,多思考底层数据结构实现。
坚持分享,坚持原创,喜欢博主的靓仔靓女们可以看看博主的首页博客!
您的点赞与收藏是我分享博客的最大赞赏!
博主博客地址: https://blog.csdn.net/weixin_43967679