Python 解LeetCode:33. Search in Rotated Sorted Array

Posted 潇湘旧友

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python 解LeetCode:33. Search in Rotated Sorted Array相关的知识,希望对你有一定的参考价值。

  • 题目描述:在一个旋转数组中查找给定的值,其中旋转数组中不含重复值;

  • 思路:
  1. 第一遍二分遍历,找到数组中最小值的索引;
  2. 第二遍分别对最小值左右两边的数组进行二分查找;
class Solution(object):

    def find_min(self, nums):
        if not nums:
            return -1
        left, right = 0, len(nums) - 1
        while nums[left] > nums[right]:
            if right - left == 1:
                return right
            mid = (left + right) / 2
            if nums[left] <= nums[mid]:
                left = mid
            if nums[right] >= nums[mid]:
                right = mid
        return 0

    def search(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        if not nums:
            return -1
        min_index = self.find_min(nums)
        if nums[min_index] == target:
            return min_index
        elif nums[min_index] > target:
            return -1
        else:
            left = self.search_t(nums, 0, min_index, target)
            if left >= 0:
                return left
            right = self.search_t(nums, min_index, len(nums)-1, target)
            if right >= 0:
                return right
        return -1

    def search_t(self, nums, left, right, target):
        while left <= right:
            mid = (left + right) / 2
            if nums[mid] == target:
                return mid
            elif nums[mid] < target:
                left = mid + 1
            else:
                right = mid - 1
        return -1

以上是关于Python 解LeetCode:33. Search in Rotated Sorted Array的主要内容,如果未能解决你的问题,请参考以下文章

Python解Leetcode: 226. Invert Binary Tree

Python 解leetcode:728. Self Dividing Numbers

Python 解leetcode:49. Group Anagrams

Python 解LeetCode:367. Valid Perfect Square

Python 解LeetCode:394 Decode String

Python解Leetcode: 539. Minimum Time Difference