LeetCode------Remove Duplicates from Sorted List
来源:互联网 发布:淘宝直通车软件 编辑:程序博客网 时间:2024/04/29 16:34
题目简介
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
.
自己的解法
public class Solution { public ListNode deleteDuplicates(ListNode head) { ListNode p = head; ListNode last =head; Set<Integer> set = new HashSet<Integer>(); while(p != null){ if (!set.contains(p.val)) { set.add(p.val); last = p; p = p.next; } else { if(p.next!=null){ last.next = p.next; p = p.next; } else{ last.next = null; p = null; } } } return head; }}
Hot解法
public ListNode deleteDuplicates(ListNode head) { if(head == null || head.next == null)return head; head.next = deleteDuplicates(head.next); return head.val == head.next.val ? head.next : head;}
public class Solution { public ListNode deleteDuplicates(ListNode head) { ListNode list = head; while(list != null) { if (list.next == null) { break; } if (list.val == list.next.val) { list.next = list.next.next; } else { list = list.next; } } return head; }}
这种解法利用了迭代,如果找到相同元素就删除,如果不是相同元素,list就进行后移。直到最后。
0 0
- Remove Duplicates from Sorted List :from LeetCode
- Leetcode - List - Remove Duplicates from Sorted List
- [leetcode][list] Remove Duplicates from Sorted List
- [leetcode][list] Remove Duplicates from Sorted List
- LeetCode: Remove Duplicates from Sorted List
- LeetCode: Remove Duplicates from Sorted List II
- [Leetcode] Remove Duplicates from Sorted List
- [Leetcode] Remove Duplicates from Sorted List II
- LeetCode: Remove Duplicates from Sorted List
- LeetCode: Remove Duplicates from Sorted List II
- [Leetcode] Remove Duplicates from Sorted List II
- leetcode 37: Remove Duplicates from Sorted List
- [leetcode] Remove Duplicates from Sorted List II
- [LeetCode] Remove Duplicates from Sorted List II
- [LeetCode] Remove Duplicates from Sorted List
- [leetcode] Remove Duplicates from Sorted List
- [leetcode] Remove Duplicates from Sorted List II
- [LeetCode]Remove Duplicates from Sorted List
- KMP匹配算法
- UVA12086 树状数组 + 裸 +单点重置
- Codeforces Round #350 (Div. 2) C. Cinema
- CodeForces 165BBurning Midnight Oil(二分)
- POJ 2236 Wireless Network【并查集】
- LeetCode------Remove Duplicates from Sorted List
- WEB服务器的搭建(腾讯云) ubuntu14.04
- 深入理解结构体指针
- [数据结构] 表达式求值(转化为后缀表达式再求值或直接求值)
- Java的Atomic类分析
- n皇后问题
- Struts2运行过程以及StrutsPrepareAndExecuteFilter源码阅读
- PAT乙级—1023. 组个最小数 (20)-native
- 删除集合里重复的字符串