[leetcode]83. Remove Duplicates from Sorted List
来源:互联网 发布:淘宝代充平台 编辑:程序博客网 时间:2024/06/06 03:27
Given a sorted linked list, delete all duplicates such that each element appear only once.
For example,
Given 1->1->2
, return 1->2
.
Given 1->1->2->3->3
, return 1->2->3
.
删除重复的节点
一开始没注意到链表是有序的,想的方法比较蠢。将没有出现过的节点存在hashmap,存在的则放在stack中,再去删除stack中的节点。
deleteNode()删除节点的原理是:如要删除i节点,先把i的下一个节点j的数据复制到i,然后把i指向j的下一个节点。这样就省去了从头节点开始查找。如果
要删除的节点为最后一个节点,仍然从头节点遍历。平均时间复杂度仍为O(1)
代码如下:
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */public class Solution { public ListNode deleteDuplicates(ListNode head) { HashMap<ListNode,Integer> map=new HashMap<>(); Stack<ListNode> stack=new Stack<>(); ListNode p=head; while(p!=null){ if(map.containsValue(p.val)){ stack.push(p); }else{ map.put(p, p.val); } p=p.next; } while(!stack.empty()){ deleteNode(head, stack.pop()); } return head; } public void deleteNode(ListNode head,ListNode node){ if(head==null||node==null){ return; } else if(head==node){ head=null; } else{ if(node.next==null){ ListNode p=head; while(p.next.next!=null){ p=p.next; } p.next=null; } else{ node.val=node.next.val; node.next=node.next.next; } } }}
由于链表是有序的,所以节点是否重复,只需要与它的下一个比较就可以了
代码如下:
public class Solution { public ListNode deleteDuplicates(ListNode head) { if (head == null) { return null; } ListNode node = head; while (node.next != null) { if (node.val == node.next.val) { node.next = node.next.next; } else { node = node.next; } } return head; }}
1 0
- [LeetCode]83.Remove Duplicates from Sorted List
- [Leetcode] 83. Remove Duplicates from Sorted List
- LeetCode --- 83. Remove Duplicates from Sorted List
- [leetcode] 83.Remove Duplicates from Sorted List
- LeetCode 83. Remove Duplicates from Sorted List
- 【leetcode】83. Remove Duplicates from Sorted List
- 83. Remove Duplicates from Sorted List LeetCode
- leetcode 83. Remove Duplicates from Sorted List
- [LeetCode]83. Remove Duplicates from Sorted List
- 【LeetCode】83. Remove Duplicates from Sorted List
- LeetCode 83. Remove Duplicates from Sorted List
- [leetcode] 83. Remove Duplicates from Sorted List
- leetcode 83. Remove Duplicates from Sorted List
- LeetCode *** 83. Remove Duplicates from Sorted List
- LeetCode - 83. Remove Duplicates from Sorted List
- 【LeetCode】83. Remove Duplicates from Sorted List
- LeetCode 83. Remove Duplicates from Sorted List
- [LeetCode]83. Remove Duplicates from Sorted List
- 【算法】牛客网模拟题编程部分3.23日
- UVA
- JAVA多线程之——线程的实现方式
- ZSTUOJ 4270: 同源数
- 在mac系统安装Apache Tomcat的详细步骤
- [leetcode]83. Remove Duplicates from Sorted List
- Jsp中标签使用:tag 文件方式 和 tld文件方式
- javaScript采用面向对象的方式实现实现拖拽
- jq-$.extend方法使用说明
- JAD-CACHE缓存框架1.0.2版本发布
- UWP入门(十二)--数据绑定用法
- JavaScript函数三种定义形式
- 关于软件研发的一些体会总结
- Mysql之数据完整性约束与表维护语句