[JS] Remove Duplicates from Sorted List II
2022. 8. 6. 12:07
🔒 문제 (LeetCode 82)
Given the head of a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. Return the linked list sorted as well.
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.
🌊 입출력
Example 1:
Input: head = [1,2,3,3,4,4,5]
Output: [1,2,5]
Example 2:
Input: head = [1,1,1,2,3]
Output: [2,3]
🔑 해결
🌌 알고리즘 - 투포인터
첫번째 노드가 중복되어 제거할 경우를 고려하여, dummy를 head 앞에 붙여 노드 제거를 수행한다.
/**
* 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) {
const dummy = new ListNode();
dummy.next = head;
let node = dummy;
while(node.next) {
if(node.next.next && node.next.val === node.next.next.val) {
let nextNode = node.next.next.next;
while(nextNode && nextNode.val === node.next.val) {
nextNode = nextNode.next;
}
node.next = nextNode;
} else {
node = node.next
}
}
return dummy.next;
};
'코딩테스트 (JS) > 투포인터' 카테고리의 다른 글
[JS] Interval List Intersections (0) | 2022.08.07 |
---|---|
[JS] 3Sum (0) | 2022.08.06 |
[JS] Permutation in String (0) | 2022.07.29 |
[JS] Longest Substring Without Repeating Characters (0) | 2022.07.29 |
[JS] Remove Nth Node From End of List (0) | 2022.07.29 |