Search in Rotated Array

There are many ways to implement binary search.
Following is the way that is not that confusing.

class Solution(object):
    def search(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """

        i = 0
        j = len(nums) - 1

        while i + 1 < j:          ## <-- make sure i and j will end up be next to each other
            m = i + (j-i)/2

            if nums[m] == target:
                return m

            if nums[i] <= nums[m]:
                if target >= nums[i] and target <= nums[m]:
                    j = m
                else:
                    i = m
            else:
                if target >= nums[m] and target <= nums[j]:
                    i = m
                else:
                    j = m

        if len(nums) > 0 and nums[i] == target:
            return i
        elif len(nums) > 0 and nums[j] == target:
            return j
        else:
            return -1

results matching ""

    No results matching ""