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

LeetCode 35 - Search Insert Position (Easy)

by HandHand 2023. 2. 20.

 

๐Ÿ’ก ๋ฌธ์ œ

LeetCode -35๋ฒˆ

 

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

target ์ด ๋ฐฐ์—ด์— ์กด์žฌํ•  ๊ฒฝ์šฐ ํ•ด๋‹น ์š”์†Œ์˜ index๋ฅผ, ๋งŒ์•ฝ ์กด์žฌํ•˜์ง€ ์•Š์„ ๊ฒฝ์šฐ

target ์ด ์œ„์น˜ํ•ด์•ผํ•  index ๋ฅผ ๋ฐ˜ํ™˜ํ•˜๋Š” ํ•จ์ˆ˜๋ฅผ ๊ตฌํ˜„ํ•˜๋Š” ๋ฌธ์ œ์ž…๋‹ˆ๋‹ค.

๋ฌธ์ œ ์กฐ๊ฑด์—์„œ ๋”ฐ๋ผ ์ •๋ ฌ๋œ ๋ฐฐ์—ด์—์„œ ์ด๋ถ„ ํƒ์ƒ‰ ์„ ์‚ฌ์šฉํ•˜๋ฉด O(logn) ์— ํ•ด๊ฒฐํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

 

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

/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number}
 */
var searchInsert = function(nums, target) {
    let answer = null

    function findItem(head, tail) {
        if (head >= tail) {
            if (nums[head] === target) {
                answer = head
            } else {
                answer = nums[head] > target ? head : head + 1
            }

            return
        }

        const mid = head + Math.floor((tail - head) / 2)

        if (nums[mid] === target) {
            answer = mid
        } else if (nums[mid] < target) {
            findItem(mid + 1, tail)
        } else {
            findItem(head, mid - 1)
        }
    }

    findItem(0, nums.length - 1)

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

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

LeetCode 994 - Rotting Oranges (Medium)  (0) 2023.04.24
LeetCode 24 - Swap Nodes in Pairs (Medium)  (0) 2023.02.20
LeetCode 169 - Majority Element (Easy)  (2) 2023.02.05
LeetCode 733 - Flood Fill (Easy)  (0) 2022.03.07
LeetCode 229 - Majority Element II (Medium)  (0) 2022.02.22

๐Ÿ’ฌ ๋Œ“๊ธ€