본문 바로가기
IT/LeetCode

[LeetCode] 83. Remove Duplicates from Sorted List

by 강천구 2022. 10. 27.

Given the head of a sorted linked list, delete all duplicates such that each element appears only once. Return the linked list sorted as well.

 

Example 1:

Input: head = [1,1,2]
Output: [1,2]

Example 2:

Input: head = [1,1,2,3,3]
Output: [1,2,3]

 

Constraints:

  • The number of nodes in the list is in the range [0, 300].
  • -100 <= Node.val <= 100
  • The list is guaranteed to be sorted in ascending order.
반응형

주어진 ListNode에서 중복을 제거하면 된다.

최초 빈값을 체크한 후 nowNode와 nextNode를 이용하여 중복된 값이면 제거한다.

 

class Solution:
   def deleteDuplicates(self, head: 'ListNode') -> 'ListNode':
       if head == None or head.next == None:
           return head
       else:
           nowNode = head
           nextNode = head.next
       while True:
           if nowNode.val == nextNode.val:
               if nextNode.next != None:
                   nextNode = nextNode.next
                   nowNode.next = nextNode
               else:
                   nowNode.next = None
                   break
           else:
               if nextNode.next != None:
                   nowNode = nextNode
                   nextNode = nextNode.next
               else:
                   break
       return head

 

문제 출처 : https://leetcode.com/problems/remove-duplicates-from-sorted-list/

 

Remove Duplicates from Sorted List - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

Github : https://github.com/kkkkang1009/leetcode/blob/master/leetcode_83.py

 

GitHub - kkkkang1009/leetcode: leetcode

leetcode. Contribute to kkkkang1009/leetcode development by creating an account on GitHub.

github.com

 

반응형

'IT > LeetCode' 카테고리의 다른 글

[LeetCode] 91. Decode Ways  (0) 2022.12.08
[LeetCode] 88. Merge Sorted Array  (0) 2022.11.15
[LeetCode] 70. Climbing Stairs  (0) 2022.08.19
[LeetCode] 69. Sqrt(x)  (0) 2022.08.19
[LeetCode] 67. Add Binary  (0) 2022.08.19

댓글