LeetCode Algorithm Exercise (Remove Duplicate Elements in Sorted List II)

题目:

给定一个排序链表,删除所有含有重复数字的节点,只保留原始链表中 没有重复出现 的数字。

示例 1:

输入: 1->2->3->3->4->4->5
输出: 1->2->5
示例 2:

输入: 1->1->1->2->3
输出: 2->3

我的正确解答:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        if(head==null){
            return head;
        }
        ListNode temp = head;
        Set s = new HashSet();
        List c = new ArrayList();
        /**思路:第一次遍历先统计出重复的节点val,第二次遍历删除重复的节点*/
        while(temp!=null){
            if(!s.contains(temp.val)){
              s.add(temp.val); 
            }else{
              c.add(temp.val);  
            }
            temp = temp.next;
        }
        temp = head;
        while(temp.next!=null){
            if(c.contains(temp.next.val)){
                temp.next = temp.next.next;
            }else{
                temp = temp.next;
            }
        }
        if(c.contains(head.val)){
            head = head.next;
        }
        return head;
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325474953&siteId=291194637