Published:
Updated:

  • ์ •๋ง ์–ด๋ ค์šด ๋ฌธ์ œ์˜€๋‹ค.
    • pivot index์˜ ๊ฐœ๋…์„ ์ดํ•ดํ•ด์•ผ ํ•œ๋‹ค.
    • ์™ผ์ชฝ ์ ˆ๋ฐ˜๊ณผ ์˜ค๋ฅธ์ชฝ ์ ˆ๋ฐ˜์„ ๊ฐ๊ฐ ๋ถ„๋ฆฌํ•˜์—ฌ ์ƒ๊ฐํ•ด์•ผ ํ•œ๋‹ค.
  • ์ฃผ์„์„ ์ž˜ ๋ณด๋ฉด ์ดํ•ดํ•˜๊ธฐ ์‰ฌ์šธ ๊ฒƒ์ด๋‹ค.


Solution

from typing import List


class Solution:
    def search(self, nums: List[int], target: int) -> int:
        lt, rt = 0, len(nums) - 1
        while lt <= rt:
            # (rt - lt) // 2: ํƒ์ƒ‰ ๋ฒ”์œ„์˜ ์ค‘๊ฐ„ ์ธ๋ฑ์Šค
            # ๊ฑฐ๊ธฐ์— lt๋ฅผ ๋”ํ•˜๋ฉด -> ์‹ค์ œ ์ค‘๊ฐ„ ์ธ๋ฑ์Šค๊ฐ€ ๋จ
            mid = (rt - lt) // 2 + lt

            if nums[mid] == target:
                return mid

            # ์™ผ์ชฝ ์ ˆ๋ฐ˜์ด ์ •๋ ฌ๋˜์—ˆ์œผ๋ฉด
            if nums[lt] <= nums[mid]:
                # ์™ผ์ชฝ ์ ˆ๋ฐ˜์—์„œ target์„ ์ฐพ์•„์•ผ ํ•˜๋Š”์ง€ ํ™•์ธ
                if nums[mid] > target >= nums[lt]:
                    # nums[mid]๊ฐ€ target๋ณด๋‹ค ํฌ๋‹ˆ ๋‹น์—ฐํžˆ ๋นผ์ค˜์•ผ ๋จ 
                    mid -= rt
                    rt -= 1
                    continue

                mid += lt
                lt += 1
                continue

            # ์˜ค๋ฅธ์ชฝ ์ ˆ๋ฐ˜์ด ์ •๋ ฌ๋˜์—ˆ์œผ๋ฉด
            # ์˜ค๋ฅธ์ชฝ ์ ˆ๋ฐ˜์—์„œ target์„ ์ฐพ์•„์•ผ ํ•˜๋Š”์ง€ ํ™•์ธ
            if nums[mid] < target <= nums[rt]:
                # nums[mid]๊ฐ€ target๋ณด๋‹ค ์ž‘์œผ๋‹ˆ ๋‹น์—ฐํžˆ ๋”ํ•ด์ค˜์•ผ ๋จ 
                mid += lt
                lt += 1
                continue

            mid -= rt
            rt -= 1

        return -1


Reference

Leave a comment