Python Simple Solution


  • 0
    D
    class Solution(object):
        def search(self, nums, target):
            """
            :type nums: List[int]
            :type target: int
            :rtype: int
            """
            def search(i, j):
                if i > j: return -1
                if nums[i] == target: return i
                if nums[j] == target: return j
                mid = (i+j)/2
                if nums[mid] == target: return mid
                if nums[mid] > nums[i]:
                    if target > nums[i] and target < nums[mid]: return search(i, mid - 1)
                    return search(mid+1, j)
                if target > nums[mid] and target < nums[j]: return search(mid+1, j)
                return search(i, mid-1)
            return search(0, len(nums) - 1)

  • 0
    M

    @dengl11 said in Python Simple Solution:

    class Solution(object):
        def search(self, nums, target):
            """
            :type nums: List[int]
            :type target: int
            :rtype: int
            """
            def search(i, j):
                if i > j: return -1
                if nums[i] == target: return i
                if nums[j] == target: return j
                mid = (i+j)/2
                if nums[mid] == target: return mid
                if nums[mid] > nums[i]:
                    if target > nums[i] and target < nums[mid]: return search(i, mid - 1)
                    return search(mid+1, j)
                if target > nums[mid] and target < nums[j]: return search(mid+1, j)
                return search(i, mid-1)
            return search(0, len(nums) - 1)
    

    You may wish to avoid recursion to enhance your speed further, as function call overheads in python are high.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.