LeetCode 852. Peak Index in a Mountain Array

๐Ÿ—“๏ธ Daily LeetCoding Challenge July, Day 25

(23.07.25) LeetCode์—์„œ๋Š” ์ผ๋ช… Daily Challenge๋ฅผ ์ œ๊ณตํ•˜๋Š”๋ฐ, ํ•˜๋ฃจ์— ํ•˜๋‚˜์”ฉ ํ’€์–ด๋‚˜๊ฐ€๋ฉด ๋‹ค์–‘ํ•œ ์•Œ๊ณ ๋ฆฌ์ฆ˜ ๋ฌธ์ œ๋“ค์„ ํ’€์–ด๋ณผ ์ˆ˜ ์žˆ์–ด์„œ ์œ ์ตํ•˜๋‹ค. ๋ณดํ†ต ๋‹ค๋ฅธ ๋ฌธ์ œ๋“ค์€ Editoral ๋ถ€๋ถ„์ด ์ž ๊ธˆ๋˜์–ด์žˆ์–ด Premium User๊ฐ€ ์•„๋‹ˆ๋ฉด ์ฝ์ง€ ๋ชปํ•˜๋Š”๋ฐ, Daily Challenge๋งŒํผ์€ ๊ณต๊ฐœ๋˜์–ด ์ž์‹ ์˜ ํ’€์ด์™€ ๋น„๊ตํ•ด๋ณผ ์ˆ˜ ์žˆ๋‹ค. LeetCode์— ์ž…๋ฌธํ•œ์ง€ ์ด์ œ ๊ฒจ์šฐ 3์ผ์ด์ง€๋งŒ, ๋‹ค๋ฅธ ์•Œ๊ณ ๋ฆฌ์ฆ˜ ์‚ฌ์ดํŠธ์— ๋น„ํ•ด์„œ ์ฒด๊ณ„๊ฐ€ ํ™•์‹คํžˆ ์ž˜ ์žกํ˜€์žˆ์–ด์„œ ์œ ์ €๋“ค์—๊ฒŒ ๋งค์šฐ ํŽธ๋ฆฌํ•˜๊ฒŒ ๋‹ค๊ฐ€์˜จ๋‹ค.

์ด๋ฒˆ ๋ฌธ์ œ๋Š” ๋ฐฐ์—ด์˜ ์ฆ๊ฐ€ํ•˜๋‹ค๊ฐ€ ๊ฐ์†Œํ•˜๋Š” ์ˆ˜์—ด์˜ ๊ทน๊ฐ’์˜ index์„ ๊ตฌํ•˜๋Š” ๋ฌธ์ œ๋‹ค. ๋ณด์ž๋งˆ์ž ์ด๋ถ„ํƒ์ƒ‰(binary-search) ์•Œ๊ณ ๋ฆฌ์ฆ˜์„ ์‚ฌ์šฉํ•ด์•ผ๊ฒ ๋‹ค๊ณ  ์ƒ๊ฐ์ด ๋“ค์—ˆ๋‹ค. ๋ฌธ์ œ ์กฐ๊ฑด์—์„œ๋„ O(logn) ์‹œ๊ฐ„ ๋ณต์žก๋„๋ฅผ ์‚ฌ์šฉํ•˜๋ผ๊ณ  ์ œ์‹œ๋˜์–ด์žˆ๊ธฐ์— ํ™•์‹ ์„ ๊ฐ€์ง€๊ณ  ๋ฌธ์ œ๋ฅผ ํ’€์—ˆ๋‹ค.

๋‚˜์˜ ํ’€์ด

class Solution:
    def peakIndexInMountainArray(self, arr: List[int]) -> int:
        result = self.binary_search(arr, 0, len(arr)-1)
        return result

    # binary search
    def binary_search(self, arr, start, end):
        while start < end:
            mid = start + (end-start)//2
            if arr[mid-1] < arr[mid] < arr[mid+1]:
                start = mid
            elif arr[mid-1] > arr[mid] > arr[mid+1]:
                end = mid
            else:
                return mid
        return -1

์ด ๋ฌธ์ œ ํ•œ์ •ํ•ด์„œ๋Š” ์ด๋Ÿฐ ํ’€์ด๋„…

์ด ๋ฌธ์ œ๊ฐ™์€ ๊ฒฝ์šฐ ๋งค์šฐ ์นœ์ ˆํ•˜๊ฒŒ๋„ ์•„์ฃผ ์ด์ƒ์ ์ธ ๋ฐฐ์—ด๋งŒ์„ ์ œ๊ณตํ•œ๋‹ค. ๋”ฐ๋ผ์„œ ์‚ฐ์˜ ๊ผญ๋Œ€๊ธฐ์— ํ•ด๋‹นํ•˜๋Š” ์ˆซ์ž๊ฐ€ ๊ณง ์ตœ๋Œ€๊ฐ’์ด๋ผ ๋‹ค์Œ๊ณผ ๊ฐ™์ด ํ’€์ˆ˜๋„ ์žˆ๋‹ค. ํ•˜์ง€๋งŒ, ๊ผญ๋Œ€๊ธฐ๊ฐ€ ์—ฌ๋Ÿฌ๊ฐœ์ธ ์ˆ˜์—ด์ด๋‚˜ ๊ผญ๋Œ€๊ธฐ๊ฐ€ ํ‰ํ‰ํ•œ ์ˆ˜์—ด(์ตœ๋Œ“๊ฐ’์ด ์—ฌ๋Ÿฌ๊ฐœ)์˜ ๊ฒฝ์šฐ ์ ์šฉ์ด ํž˜๋“ค๊ธฐ์— ์ถ”์ฒœํ•˜์ง„ ์•Š๋Š”๋‹ค. ์ผ๋ฐ˜ํ™”๊ฐ€ ์–ด๋ ต๊ธฐ์— ์ด๋Ÿฐ ํ’€์ด๋Š” short coding์—๋Š” ๋„์›€์ด ๋˜์ง€๋งŒ ๊ถŒํ•˜์ง„ ์•Š๋Š”๋‹ค.

class Solution:
    def peakIndexInMountainArray(self, arr: list[int]) -> int:
        return arr.index(max(arr))

์—ฌ๋‹ด

ํ™•์‹คํžˆ ๋ฐฑ์ค€์— ๋น„ํ•ด์„œ LeetCode๋Š” C++ ์นœํ™”์ (?) ํ”Œ๋žซํผ์ธ ๋“ฏ ํ•˜๋‹ค. ์•„๋ฌด๋ž˜๋„ ์˜ค๋žฌ๋™์•ˆ ์•Œ๊ณ ๋ฆฌ์ฆ˜์„ ๊ณต๋ถ€ํ•˜์…จ๋˜ ๋ถ„๋“ค์€ C๋‚˜ C++๋กœ ์‹œ์ž‘ํ•˜์…จ๋˜ ๋ถ„๋“ค์ด ๋งŽ์œผ์‹œ๋‹ˆ๊นŒ ์‚ฌ์šฉ์ธต์ด ๋‘ํˆผํ•ด์„œ ๊ทธ๋Ÿฐ ๊ฒฝํ–ฅ์ด ์ƒ๊ธฐ๋Š” ๊ฒƒ ๊ฐ™๋‹ค. Solution์˜ ํ’ˆ์งˆ๋„ Python๋ณด๋‹ค๋Š” C++์ด ํ›จ์”ฌ ์œ ์ตํ•œ ๊ฒฝ์šฐ๊ฐ€ ๋งŽ์€๋ฐ, ๊ทธ๋ƒฅ C++ ๊ณต๋ถ€ํ•ด์„œ ์•Œ๊ณ ๋ฆฌ์ฆ˜ ์–ธ์–ด๋ฅผ ๋ฐ”๊ฟ”๋ณผ๊นŒ ์ƒ๊ฐ์ค‘์ด๋‹ค.