[Algorithm/JavaScript] Remove Duplicates from Sorted List

Dicoยท2021๋…„ 1์›” 13์ผ
0

[Algorithm/JavaScript]

๋ชฉ๋ก ๋ณด๊ธฐ
16/18

Leetcode #83 Algorithm Question Review ๐Ÿฆฉ


๋ฌธ์ œ์ถœ์ฒ˜: https://leetcode.com/problems/remove-duplicates-from-sorted-list/

๋ฌธ์ œ

๋ฌธ์ œ ๋ณด๋Ÿฌ๊ฐ€๊ธฐ


์ œ์ถœ๋‹ต์•ˆ

/**
 * 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}
 ์กฐ๊ฑด:
 - ๋…ธ๋“œ value๋Š” -100 ๋ถ€ํ„ฐ 100 ๊นŒ์ง€ ์žˆ์Œ.
 - ๋…ธ๋“œ์˜ ์ˆ˜๋Š” ์ตœ๋Œ€ 300๊ฐœ๊นŒ์ง€ ์žˆ์Œ.
 - ๋…ธ๋“œ๋Š” ๋ฌด์กฐ๊ฑด ์˜ค๋ฆ„์ฐจ์ˆœ์œผ๋กœ ์ •๋ ฌ๋˜์–ด ์žˆ๋‹ค.
   1) 1์ฐจ์ ์œผ๋กœ ํฌ๊ธฐ ์ˆœ์œผ๋กœ ์ •๋ ฌ์ด ๋˜์–ด์žˆ์Œ. ์ค‘๋ณต๊ฐ’๋งŒ ์—†์• ๋ฉด ๋œ๋‹ค.
   2) prevVal๊ณผ curVal์„ ๋น„๊ต
   3) ๋น„๊ตํ•ด์„œ value๊ฐ€ ๊ฐ™์„ ๊ฒฝ์šฐ, curNode๋ฅผ ์—†์• ๊ณ  prevNode์™€ nextNode๋ฅผ ์ด์–ด์ค˜์•ผํ•œ๋‹ค.
 - ๋ฐ˜ํ™˜ํ•˜๋Š” ๋งํฌ๋“œ๋ฆฌ์ŠคํŠธ๋„ ์˜ค๋ฆ„์ฐจ์ˆœ์œผ๋กœ ์ •๋ ฌ์ด ๋˜์–ด์žˆ์–ด์•ผ ํ•œ๋‹ค.
 - input, output ์ „๋ถ€ linked list๋กœ!
 */
const deleteDuplicates = function(head) {
    let cur = head;
    if (head !== null && head.next){ //โ—๏ธ Runtime Error๋ฅผ ๋งˆ์ฃผํ–ˆ๋˜ ๊ตฌ๊ฐ„
        cur = head.next;
        prevNode = head;
      
        if (prevNode.val === cur.val){ 
            cur = cur.next
            prevNode.next = cur; 
        }

        while (cur !== null && cur.next){ 
            if(cur !== null && prevNode.val === cur.val){ 
                cur = cur.next;
                prevNode.next = cur; 
            } else { 
                prevNode = cur;
                cur = cur.next;
            }
        }
        if (cur !== null && prevNode.val === cur.val){
            prevNode.next = null;
        }
    } else {
        return head;
    }
    return head;
};

์˜ค๋Š˜์˜ Lesson

  • Singly-Linked List ์ž๋ฃŒ๊ตฌ์กฐ๋ฅผ ์ด์šฉํ•œ ๋ฌธ์ œ.
  • ํ•จ์ˆ˜ ๋‚ด๋ถ€์˜ ์ฒซ๋ฒˆ์งธ if๋ฌธ(if (head.next))์—์„œ runtime error์˜ ์›์ธ์„ ๋ถ„์„ํ•˜๋Š๋ผ ์‹œ๊ฐ„์„ ๋งŽ์ด ๋ณด๋ƒˆ๋‹ค.
    ํ•œ์ฐธ์„ ํ—ค๋งค์ด๋‹ค๊ฐ€ ํŒ€์›๋“ค์˜ ์˜๊ฒฌ์„ ๊ตฌํ–ˆ๋Š”๋ฐ, ์•Œ๊ณ ๋ณด๋‹ˆ ์ด์œ ๋Š” ์ด๋Ÿฌํ–ˆ๋‹ค:
    head์— null๊ฐ’์ด ๋“ค์–ด์˜ฌ ์ˆ˜๋„ ์žˆ๋Š”๋ฐ, null์ด๋ผ๋ฉด head.next์—๋Š” ์•„์˜ˆ ์ ‘๊ทผํ•  ์ˆ˜๊ฐ€ ์—†์–ด์„œ null์ฒดํฌ๋ฅผ ๋จผ์ € ํ•ด์•ผํ•˜๊ธฐ ๋•Œ๋ฌธโ—๏ธ
    head !== null ์„ ์กฐ๊ฑด๋ฌธ์— ์ถ”๊ฐ€ํ•จ์œผ๋กœ์จ ๋ฌธ์ œ๋ฅผ ํ•ด๊ฒฐํ•  ์ˆ˜ ์žˆ์—ˆ๋‹ค...!
//val๊ณผ next์˜ ์กฐ๊ฑด
function ListNode(val, next) {
    this.val = (val===undefined ? 0 : val)
    this.next = (next===undefined ? null : next)
}
  • ๊ฐ’์— null์ด ๋“ค์–ด์˜ฌ ์ˆ˜ ์žˆ๋Š” ๋ฌธ์ œ๋ผ๋ฉด, null ์ฒดํฌํ•˜๋Š” ๊ฒƒ ์žŠ์ง€์•Š๊ธฐ โœ…
profile
ํ”„๋ฆฐ์ด์˜ ์ฝ”๋ฌป์€ ์ฝ”๋“œ๊ฐ€ ์Œ“์ด๋Š” ๊ณต๊ฐ„

0๊ฐœ์˜ ๋Œ“๊ธ€