본문 바로가기
LeetCode/코딩 테스트 스터디 3주차

[LeetCode] 83. Remove Duplicates from Sorted List 풀이 (JS)

by inwoo1324 2022. 7. 24.

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
Input: head = [1,1,2]
Output: [1,2]
#2
Input: head = [1,1,2,3,3]
Output: [1,2,3]

 

1.언어

자바스크립트(JavaScript)

 

2. 문제 풀이

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;
};
Runtime: 92 ms, faster than 69.34% of JavaScript online submissions for Remove Duplicates from Sorted List.
Memory Usage: 44.5 MB, less than 30.82% of JavaScript online submissions for Remove Duplicates from Sorted List.
 

현재 노드 값과 다음 노드 값이 같을 시 next 링크를 다음 노드로 연결