복's
[ LeetCode - 83 ] Remove Duplicates from Sorted List 본문
https://leetcode.com/problems/remove-duplicates-from-sorted-list/description/
Remove Duplicates from Sorted List - LeetCode
Can you solve this real interview question? Remove Duplicates from Sorted List - 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: [https://assets.le
leetcode.com
생각보다 자주 나오는 Linked List 문제 !!!
푸는데 크게 어렵지 않았지만, 시간은 조금 걸렸다.
생각보다 예외에 걸려서 예외 케이스 처리가 미흡했다고 본다.
자료 구조를 알고 있다고, 잘 푸는거랑은 다른건지 잘 몰라서 못 시간이 쫌 걸린건지는 알 수 없다...ㅎ
[ 📌 풀이 ]
⚙︎ 반드시 해야 할 것: head를 기억하기 (head를 기억해두지 않으면 다시 못 찾을 수 있다.)
리스트의 이전 노드와 현재노드를 기억하고 있다가 두 노드가 가진 value가 같다면 이전 노드와 현재 노드의 다음 노드를 이어준다.
(중복에 있는 중복되는 값을 가진 노드는 이전 노드에 의해서만 참조(next에)되고 있기 때문에 자연스럽게 연결이 끊긴다.)
[ 📌 코드 - Python ]
"""
# Author : Lee In Bok
# Date : 2023.11.08(Wed)
# Spend Time: 18m 40s
# Runtime : 46 ms (Beats 58.11%)
# Memory : 16.3 MB (Beats 53.09%)
# Algoritm : 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]:
prev = None
temp = head
while temp:
if prev and prev.val == temp.val:
prev.next = temp.next
else:
prev = temp
temp = temp.next
return head
[ 📌 코드 - Java ]
/**
* Author : Lee In Bok
* Date : 2023.11.08(Wed)
* Spend Time: 18m 40s
* Runtime : 0 ms (Beats 100%)
* Memory : 42.6 MB (Beats 87.50%)
* Algoritm : Linked List
*/
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode deleteDuplicates(ListNode head) {
ListNode temp = head;
ListNode prev = null;
while(temp != null){
if(prev != null && prev.val == temp.val){
prev.next = temp.next;
} else {
prev = temp;
}
temp = temp.next;
}
return head;
}
}
두 코드다 속도랑 메모리를 크게 사용하지 않기 때문에 매번 돌릴 때 마다 결과(Beats)는 다르게 나온다.
[ 📌 결과 - Python ]
[ 📌 결과 - Java ]
'알고리즘 > LeetCode' 카테고리의 다른 글
[ LeetCode - 175 ] Combine Two Tables (1) | 2023.11.11 |
---|---|
[ LeetCode - 88 ] Merge Sorted Array (0) | 2023.11.11 |
[ LeetCode - 69 ] Sqrt(x) (0) | 2023.11.05 |
[ LeetCode - 67 ] Add Binary (1) | 2023.11.04 |
[ LeetCode - 66 ] Plus One (1) | 2023.11.03 |