관리 메뉴

솜씨좋은장씨

[leetCode] 82. Remove Duplicates from Sorted List II (Python) 본문

Programming/코딩 1일 1문제

[leetCode] 82. Remove Duplicates from Sorted List II (Python)

솜씨좋은장씨 2020. 12. 2. 00:09
728x90
반응형

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

Return the linked list sorted as well.

 

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

Solution

from collections import Counter

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def deleteDuplicates(self, head: ListNode) -> ListNode:
        list_nums = []
        
        while head != None:
            list_nums.append(head.val)
            head = head.next
            
        
        cnt_items = [ num[0] for num in Counter(list_nums).items() if num[1] == 1]
        
        answerList = ListNode(0) 
        
        result = answerList 
        
        for num in cnt_items: 
            answerList.next = ListNode(num) 
            answerList = answerList.next 
        return result.next

 

SOMJANG/CODINGTEST_PRACTICE

1일 1문제 since 2020.02.07. Contribute to SOMJANG/CODINGTEST_PRACTICE development by creating an account on GitHub.

github.com

 

Comments