您的位置:首页 > 其它

83. Remove Duplicates from Sorted List

2017-02-17 12:34 239 查看
 题目

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.

我的解法

/**
* 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<Integer, Integer> map = new HashMap<>();
ListNode prev = new ListNode(-1);
ListNode res = prev;
while(head != null){
if(!map.containsKey(head.val)){
map.put(head.val, 1);
prev.next = head;
prev = head;
}
prev.next = head.next;
head = head.next;
}
return res.next;
}
}算法分析:没有利用排序好这个性质,时间、空间复杂度都为O(n)。

答案解法(简便、递归)

/**
* Definition for singly-linked list.
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) { val = x; }
* }
*/
public class Solution {
// 删除head链表中重复元素
public ListNode deleteDuplicates(ListNode head) {
// 只有一个节点时返回其本身
if(head == null || head.next == null)
return head;
// 删除子链表中重复元素,并插入head节点后
head.next = deleteDuplicates(head.next);
// 若head和子链表head元素重复,则选择子链表
return head.val == head.next.val ? head.next : head;
}
}
算法分析:递归思想。用头结点和无重复元素的子链表(递归生成)生成新的链表。

答案解法二(利用排序特性):

我的代码

/**
* 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) {
if(head == null)
return head;
ListNode res = head;
ListNode prev = head;
head = head.next;
while(head != null){
if(head.val != prev.val){
prev.next = head;
prev = head;
}
else
prev.next = head.next;
head = head.next;
}
return res;
}
}
算法思路:把当前节点和前节点比较,判断是否插入当前节点。

答案代码

/**
* 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) {
ListNode l = head;
while(head != null){
if(head.next == null)
break;
//如果下一节点和头节点值相等,则更新头结点的下一节点
if(head.val == head.next.val)
head.next = head.next.next;
else
// 否则更新头节点
head = head.next;
}
return l;
}
}


算法思路:当前节点和下节点比较,判断是否插入下节点还是下下节点。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: