leetcode Remove Duplicates from Sorted List II题解

    xiaoxiao2022-07-02  112

    题目描述:

    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

    中文理解:

    给定一个递增有序的链表,删除其中元素值重复的节点,返回删除后的链表。

    解题思路:

    使用hashmap来存储每个节点元素出现的次数,当出现次数为1时,将这个元素建立节点,添加到链表中。

    代码(java):

    /** * 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; HashMap<Integer,Integer> map=new HashMap(); ListNode p=head; while(p!=null){ if(map.containsKey(p.val)){ map.put(p.val,map.get(p.val)+1); } else map.put(p.val,1); p=p.next; } ListNode res=new ListNode(0); ListNode cur=res; while(head!=null){ if(map.get(head.val)==1){ cur.next=new ListNode(head.val); cur=cur.next; } head=head.next; } return res.next; } }

     

    最新回复(0)