Saturday, August 15, 2015

Leetcode 33. Search in Rotated Sorted Array

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

Due to Python's powerful built-in functions, we have a slick solution:
        try:
            return nums.index(target)
        except:
            return -1
Run Time is 60 ms.

The normal way is to use binary search. Because there can be at most 1 turning point, the update of bounds is not complex.

Solution:
# T:O(lgn) S:O(1)
class Solution:
    # @param A, a list of integers
    # @param target, an integer to be searched
    # @return an integer
    def search(self, A, target):
        low, high = 0, len(A)
        
        while low < high:
            mid = low + (high - low) / 2
            
            if A[mid] == target:
                return mid
            
            if A[low] <= A[mid]:
                if A[low] <= target and target < A[mid]:
                    high = mid
                else:
                    low = mid + 1
            else:
                if A[mid] < target and target <= A[high - 1]:
                    low = mid + 1
                else:
                    high = mid
                    
        return -1
Run Time: 52 ms


No comments:

Post a Comment