Algorithm/알고리즘 문제풀이
LeetCode 83(Remove Duplicates from Sorted List, java)
devraphy
2022. 4. 17. 16:58
0. 문제
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
1. 문제 설명
- 문제에서 오름차순으로 정렬된 연결 리스트(head)가 주어진다.
- 해당 연결 리스트 내부에는 중복된 value를 가진 노드가 존재한다.
- 각 value가 한 번씩만 사용되도록 중복된 value를 가진 노드를 삭제하는 것이 문제의 핵심이다.
2. 문제 해설
a) 첫 번째 접근
- 이 문제는 직관적으로 생각하여 접근하면 되는 문제다.
- 문제에서 주어지는 연결 리스트(head)가 이미 오름차순으로 정렬되어 있기 때문이다.
- 그러므로 현재 노드(head)와 다음 노드(head.next)의 value를 비교한다.
- 중복이 존재하는 경우, head.next = head.next.next가 된다.
- 중복이 존재하지 않는 경우, head= head.next가 된다.
- 다음 코드를 보면서 이해해보자.
3. 정답 코드
class Solution {
public ListNode deleteDuplicates(ListNode head) {
if(head == null) {return head;}
ListNode result = head;
while(head.next != null) {
if(head.val == head.next.val) {
head.next = head.next.next;
}
else{
head = head.next;
}
}
return result;
}
}