(Medium #33) Search in Rotated Sorted Array

Problem

Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).
You are given a target value to search. If found in the array return its index, otherwise return -1.
You may assume no duplicate exists in the array.
Your algorithm's runtime complexity must be in the order of O(log n).
Example 1:
Input: nums = [4,5,6,7,0,1,2], target = 0
Output: 4
Example 2:
Input: nums = [4,5,6,7,0,1,2], target = 3
Output: -1

My solution

# https://leetcode.com/problems/search-in-rotated-sorted-array/discuss/145697/Python-100
class Solution:
    def search(self, nums, target):
        s, e = 0, len(nums)-1
        
        while s <= e:
            m = int((s+e) / 2)
            
            if nums[m] == target:
                return m
            elif nums[m] > target:
                if nums[m] >= nums[s]:
                    if nums[s] > target:
                        s = m+1
                    else: ## nums[s] < target
                        e = m-1                        
                else: ## nums[m] < nums[s]
                    e = m-1
            else: ## nums[m] < target
                if nums[m] >= nums[s]:
                    s = m+1
                else: ## nums[m] < nums[s]
                    if nums[e] >= target:
                        s = m+1
                    else: ## nums[e] < target
                        e = m-1                        
        return -1                        
Runtime: 52ms, Memory: 14MB
  • 참고(index함수이용): Runtime: 48ms, Memory: 14.3MB
  • why not using index() ? is it allowed?
    • I think this is because it will be O(n) solution, not O(logn) as in condition

댓글