카테고리 없음
LeetCode #83 Remove Duplicates from Sorted List(EASY)
Seongwoo
2022. 7. 19. 10:51
문제
정렬된 연결 목록의 머리가 주어지면 각 요소가 한 번만 나타나도록 모든 중복 항목을 삭제합니다. 정렬된 연결 목록도 반환합니다.
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.
제출 코드
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var deleteDuplicates = function(head) {
if (!head) {
return null;
}
let prev = head
let next = head.next;
while (next) {
if (prev.val === next.val) {
prev.next = next.next;
} else {
prev = prev.next;
}
next = next.next;
}
return head;
};
문제풀이
우선 주어진 리스트 노드의 값이 없을 수 있기 때문에 예외처리를 해준다.
그다음 두 가지 변수를 선언 후 head의 값과 그다음 값을 각각 저장해 준다.
while문을 통해 루프를 돌리며 head의 값과 그다음 값이 같은지 확인하며 해당 값을 지워준다.