码迷,mamicode.com
首页 > 编程语言 > 详细

Python 解LeetCode:33. Search in Rotated Sorted Array

时间:2017-12-14 04:10:55      阅读:173      评论:0      收藏:0      [点我收藏+]

标签:==   sel   int   logs   ota   code   数组   pos   二分查找   

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

  • 思路:
  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

标签:==   sel   int   logs   ota   code   数组   pos   二分查找   

原文地址:http://www.cnblogs.com/qiaojushuang/p/8035656.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!