파비의 매일매일 공부기록

2023.08.08 Today's Challenge 본문

Problem Solving/LeetCode

2023.08.08 Today's Challenge

fabichoi 2023. 8. 8. 23:45

https://leetcode.com/problems/search-in-rotated-sorted-array/

 

Search in Rotated Sorted Array - LeetCode

Can you solve this real interview question? Search in Rotated Sorted Array - There is an integer array nums sorted in ascending order (with distinct values). Prior to being passed to your function, nums is possibly rotated at an unknown pivot index k (1 <=

leetcode.com

이분탐색으로 풀면 되는 문제.

class Solution:
    def search(self, nums: List[int], target: int) -> int:
        n = len(nums)
        l, r = 0, n-1

        while l <= r:
            m = l + (r - l) // 2

            if nums[m] == target:
                return m
            elif nums[m] >= nums[l]:
                if target >= nums[l] and target < nums[m]:
                    r = m - 1
                else:
                    l = m + 1
            else:
                if target <= nums[r] and target > nums[m]:
                    l = m + 1
                else:
                    r = m - 1
        
        return -1
반응형

'Problem Solving > LeetCode' 카테고리의 다른 글

2023.08.10 Today's Challenge  (0) 2023.08.10
2023.08.09 Today's Challenge  (0) 2023.08.09
2023.08.07 Today's Challenge  (0) 2023.08.07
2023.08.06 Today's Challenge  (0) 2023.08.06
2023.08.05 Today's Challenge  (0) 2023.08.05
Comments