๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿƒ algorithm/leetcode

LeetCode 15 - 3Sum (Medium)

by HandHand 2023. 4. 24.

 

๐Ÿ’ก ๋ฌธ์ œ

LeetCode - 15๋ฒˆ

 

๐ŸŽฏ ํ’€์ด ๊ณผ์ •

์ฃผ์–ด์ง„ ๋ฐฐ์—ด์—์„œ 3๊ฐœ์˜ ์›์†Œ์˜ ์กฐํ•ฉ ์ค‘ ํ•ฉ์ด 0์ธ ๊ฒƒ๋“ค์„ ์ค‘๋ณต์—†์ด ๋ชจ๋‘ ์ฐพ๋Š” ๋ฌธ์ œ์ž…๋‹ˆ๋‹ค.

๋‹ค๋งŒ ์ž…๋ ฅ ํฌ๊ธฐ๋ฅผ ๊ณ ๋ คํ•ด์„œ ์ผ๋ฐ˜ ์กฐํ•ฉ ์•Œ๊ณ ๋ฆฌ์ฆ˜๋ณด๋‹ค ํšจ์œจ์ ์ธ ๋ฐฉ๋ฒ•์ด ํ•„์š”ํ•ฉ๋‹ˆ๋‹ค.

 

ํˆฌ ํฌ์ธํ„ฐ ์•Œ๊ณ ๋ฆฌ์ฆ˜์„ ํ™œ์šฉํ•˜๋ฉด, ํŠน์ • ํ•ฉ S ๋ฅผ ๋งŒ์กฑํ•˜๋Š” ๋ฐฐ์—ด ์Œ์„ ์ค‘๋ณต์—†์ด ์ฐพ๋Š”๋ฐ ํ™œ์šฉํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

์ด๋•Œ ๋ฐฐ์—ด์€ ์ •๋ ฌ์ด ๋œ ์ƒํƒœ์—ฌ์•ผํ•ฉ๋‹ˆ๋‹ค. (์ค‘๋ณต ์ œ๊ฑฐ๋ฅผ ์œ„ํ•ด)

 

์ด ๋ฌธ์ œ๋ฅผ ์•ฝ๊ฐ„ ๋ณ€ํ˜•ํ•ด๋ณด๋ฉด ์„ธ ์›์†Œ ์ค‘ ๊ฐ€์žฅ ์ฒซ๋ฒˆ์งธ ์š”์†Œ๋ฅผ pivot ์œผ๋กœ ์ •ํ•˜๊ณ ,

๋‚˜๋จธ์ง€ ๋‘ ์š”์†Œ๋Š” pivot ์„ ์ œ์™ธํ•œ ๊ตฌ๊ฐ„์—์„œ sum - arr[pivot] ์„ ์ฐพ๋Š” ๋ฌธ์ œ๋กœ ํ•ด์„ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

์ด๋•Œ ์ค‘๋ณต ์ œ๊ฑฐ๋ฅผ ์œ„ํ•ด pivot ์ด ๋ฐ”๋กœ ์ง์ „ pivot ๊ฐ’๊ณผ ๋™์ผํ•  ๊ฒฝ์šฐ ๋ฌด์‹œํ•˜๊ณ ,

๋งˆ์ฐฌ๊ฐ€์ง€๋กœ ๋‚˜๋จธ์ง€ ๋‘ ์š”์†Œ ์ค‘ ์ฒซ๋ฒˆ์งธ ์š”์†Œ์ธ head ๋ฅผ ์ •ํ•  ๋•Œ ์ด์ „ head ์™€ ๋™์ผํ•˜๋‹ค๋ฉด ๋ฌด์‹œํ•ด์ค๋‹ˆ๋‹ค.

 

๐Ÿ‘จ‍๐Ÿ’ป ์ฝ”๋“œ

/**
 * @param {number[]} nums
 * @return {number[][]}
 */
var threeSum = function(nums) {
    function twoSum(pivot) {
        const result = []

        let head = pivot + 1
        let tail = nums.length - 1

        while (head < tail) {
            const sum = nums[pivot] + nums[head] + nums[tail]

            if (sum === 0) {
                if (head > pivot + 1 && nums[head] === nums[head - 1]) {
                    head += 1
                    continue
                }

                result.push([nums[pivot], nums[head], nums[tail]])
                head += 1
            } else if (sum < 0) {
                head += 1
            } else {
                tail -= 1
            }
        }

        return result
    } 

    const answer = []

    nums.sort((a, b) => a - b)

    for (let pivot = 0; pivot < nums.length - 2; pivot += 1) {
        if (pivot > 0 && nums[pivot] === nums[pivot - 1]) {
            continue
        }

        const result = twoSum(pivot)

        answer.push(...result)
    }   

    return answer
};
๋ฐ˜์‘ํ˜•

'๐Ÿƒ algorithm > leetcode' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

LeetCode 2390 - Removing Stars From a String (Medium)  (0) 2023.04.24
LeetCode 1603 - Design Parking System (Easy)  (0) 2023.04.24
LeetCode 13 - Roman to Integer (Easy)  (0) 2023.04.24
LeetCode 994 - Rotting Oranges (Medium)  (0) 2023.04.24
LeetCode 24 - Swap Nodes in Pairs (Medium)  (0) 2023.02.20

๐Ÿ’ฌ ๋Œ“๊ธ€