【LeetCode】82. Remove Duplicates from Sorted List II

Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.

Example 1:

Input: 1->2->3->3->4->4->5
Output: 1->2->5

Example 2:

Input: 1->1->1->2->3
Output: 2->3

题目:给定一个有序链表,剔除重复的数字节点。


思路1:第一次遍历使用HashMap存储每个数出现的次数,第二次遍历直接从HashMap中获取之前存储的值,等于1的节点保留。该方法耗时较长。

思路2:多定义两个节点指针,遍历整个链表,其过程有点复杂,容易考虑不周到

pos指向当前遍历到的节点。node指向链表保留节点末尾;head为该数值首次出现的节点。一般head在node后。

/**
 * 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||head.next==null)
            return head;
        ListNode node = null;
        ListNode ret = null;
        //ListNode pre = head;
        ListNode pos = head.next;
        int count = 1;
        while(pos!=null){
            //count++;
            if(head.val != pos.val){
                if(count==1){                    
                    if(ret==null){
                        //ret=pre;
                        node=head;
                        ret=node;
                    }
                    else{
                        node.next=head;
                        node=node.next;
                    }  
                    //node=node.next;
                }
                head = pos;
                count=0;
            }
            count++;
            pos=pos.next;
        }

        if(count==1){
            //node.next = pre;
            if(node==null){
                node=head;
                ret=node;                    
            }
            else{
                node.next=head;
                node=node.next;
            }
            node.next = null;   
        }
        if(ret!=null)
            node.next = null;
        return ret;
    }
}

本来定义了pre代替head,耗时为2ms,直接用head耗时1ms,打败100%solution....

Interesting...

猜你喜欢

转载自blog.csdn.net/hc1017/article/details/80161294