물음표 살인마의 개발블로그

알고리즘 문제/Leetcode

83. Remove Duplicates from Sorted List

BEstyle 2023. 1. 20. 01:34

iven 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.

# https://leetcode.com/problems/remove-duplicates-from-sorted-list/


'''
1. 아이디어 :
    1) 포인터를 두개 두고, while문을 2번 돌리면서, curr.val과 curr.next.val이 같으면 curr.next를 curr.next.next로 바꾼다.
2. 시간복잡도 :
    1) (n)
3. 자료구조 :
    1) Linked List

'''
# 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: Optional[ListNode]) -> Optional[ListNode]:
        curr = head
        while curr:
            while curr.next and curr.val == curr.next.val:
                curr.next = curr.next.next
            curr = curr.next
        return head

'알고리즘 문제 > Leetcode' 카테고리의 다른 글

938. Range Sum of BST  (0) 2023.01.21
382. Linked List Random Node  (0) 2023.01.20
2181. Merge Nodes in Between Zeros  (0) 2023.01.17
160. Intersection of Two Linked Lists  (0) 2023.01.17
240. Search a 2D Matrix II  (0) 2023.01.17