33. Search in Rotated Sorted Array

2021. 10. 26. 01:43Leetcode

Description:

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 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For example, [0,1,2,4,5,6,7] might be rotated at pivot index 3 and become [4,5,6,7,0,1,2].

Given the array nums after the possible rotation and an integer target, return the index of target if it is in nums, or -1 if it is not in nums.

You must write an algorithm with O(log n) runtime complexity.

 

'''
[1] binary search)

idea::
1. first find minimum_idx
2. left=minimum_idx, right=(minimum_idx-1)%len(nums), do binary search

code::


-T/C: O(logn) # two-binary search. 
-S/C: O(1)
'''

class Solution:
    def search(self, nums: List[int], target: int) -> int:
        left=0
        right=len(nums)-1
        
        # find min_idx
        while left<right:
            mid=left+(right-left)//2
            
            if nums[mid]>nums[right]:
                left=mid+1
            else:
                right=mid
        
        # at this time. need to find what is smaller num
        if nums[left]>nums[right]:
            left=right
        
        # do binary search
        right=left+len(nums)-1  # imagine values higher than min_val are appended to nums
        
        while left<=right:
            mid=left+(right-left)//2
            mid_idx=mid % len(nums)
            if nums[mid_idx]==target:
                return mid_idx
            elif nums[mid_idx]>target:
                right=mid-1
            else:
                left=mid+1
                
        return -1

'Leetcode' 카테고리의 다른 글

226. Invert Binary Tree  (0) 2021.10.26
371. Sum of Two Integers  (0) 2021.10.26
199. Binary Tree Right Side View  (0) 2021.10.25
103. Binary Tree Zigzag Level Order Traversal  (0) 2021.10.25
860. Lemonade Change  (0) 2021.10.24