Wednesday, August 2, 2017

[Leetcode] 81. Search in Rotated Sorted Array II

This problem doesn't look like a hard problem, but is very tricky. I guess there are two key points:

  1. how to handle repeated numbers (I did not think it through)
  2. figure out which part of the array to search

class Solution(object):
    def search(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: bool
        """
        start = 0
        end = len(nums) - 1
        while start <= end:
            mid = (start + end) / 2
            if nums[mid] == target: 
                return True
            
            while start < mid and nums[start] == nums[mid]:
                # tricky part, remove the repeatation
                start += 1
                
            if nums[start] == target or nums[end] == target:
                return True
            
            if nums[start] <= nums[mid]:
                # rotation point is behind the mid point
                # first part is in order
                if nums[start] < target < nums[mid]:
                    end = mid - 1
                else:
                    start = mid + 1
            else:
                # rotation point is before the mid point
                # second part is in order
                if nums[mid] < target < nums[end]:
                    start = mid + 1
                else:
                    end = mid -1

        return False

No comments:

Post a Comment