LeetCode Solutions : Remove Duplicates from Sorted List
2014-11-19 19:10
281 查看
【题目描述】
Given a sorted linked list, delete all duplicates such that each element appear only once.
For example,
Given
Given
【编程步骤】
* 1. 处理特殊情况:如果该链表为空或只有一个结点,说明此链表没有重复的元素,直接返回头指针head;
即:if(head==null||head.next==null)
return head;
* 2. 定义遍历指针visited,如果当前结点的值等于下个结点的值,说明存在副本,则移除下个结点;否则继续往下遍历;即
【代码实现】
由于只需要遍历一次,故时间复杂度为O(n),空间复杂度为O(1)
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.
【编程步骤】
* 1. 处理特殊情况:如果该链表为空或只有一个结点,说明此链表没有重复的元素,直接返回头指针head;
即:if(head==null||head.next==null)
return head;
* 2. 定义遍历指针visited,如果当前结点的值等于下个结点的值,说明存在副本,则移除下个结点;否则继续往下遍历;即
while(visited!=null&&visited.next!=null){ if(visited.val==visited.next.val) visited.next=visited.next.next; else visited=visited.next; }
【代码实现】
/**【复杂度分析】
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode deleteDuplicates(ListNode head) {
if(head==null||head.next==null)
return head;
ListNode visited=head;
while(visited!=null&&visited.next!=null){ if(visited.val==visited.next.val) visited.next=visited.next.next; else visited=visited.next; }
return head;
}
}
由于只需要遍历一次,故时间复杂度为O(n),空间复杂度为O(1)
相关文章推荐
- leetcode 38: Remove Duplicates from Sorted List II
- LeetCode - Remove Duplicates from Sorted List
- leetcode 37: Remove Duplicates from Sorted List
- LeetCode_Remove Duplicates from Sorted List II
- LeetCode Online Judge 题目C# 练习 - 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] Remove Duplicates from Sorted List
- Leetcode: Remove Duplicates from Sorted List
- leetcode 38: Remove Duplicates from Sorted List II
- [LeetCode] Remove Duplicates from Sorted List
- [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 II, Solution
- [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