33. Search in Rotated Sorted Array

题目介绍

Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., 0 1 2 4 5 6 7might become 4 5 6 7 0 1 2).
You are given a target value to search. If found in the array return its index, otherwise return -1.
You may assume no duplicate exists in the array.

代码(python):

class Solution(object):
    def size(self,range_tuble):
        self.tuble_size = range_tuble[1] - range_tuble[0]
        return self.tuble_size

    def search(self,nums,target):
        if len(nums) == 0:
            return -1
        range_tuble = (0,len(nums) - 1)
        start = 0
        end = len(nums) - 1
        while self.size(range_tuble) >= 0:
            mid = (start + end)//2
            if(nums[mid] == target):
                return mid
            if(nums[mid] >= nums[start]):
                if(target >= nums[start] and target <= nums[mid]):
                    end = mid - 1
                    range_tuble = (start,end)
                else:
                    start = mid + 1
                    range_tuble = (start,end)
    
            else:
                if(target >= nums[start] or target <= nums[mid]):
                    end = mid - 1
                    range_tuble = (start,end)
                else:
                    start = mid + 1
                    range_tuble = (start,end)
        return -1

代码分析:

代码思路:

由于是旋转的则说明始终是有两段有序数列可以进行折半查找的

代码解析

首先因为是旋转的情况
分为两段,一段为数值较大的区域,一段为数值较小的区域
总体上有两种情况:
1.中间的位置在数值较大的区域
1.1 如果目标值target大于数组的第一个值而小于mid的话则目标值处于一个
递增的数列中,直接可以进行binary_search
1.2 如果没有则目标值处于一个混合的地方有部分的大值区域,有部分的小值的区域
继续减小范围
2.中间的值在数值较小的区域
2.1 如果target > 数组的第一个值或者小于mid的值,则说明在左侧的混合的区域

你可能感兴趣的:(33. Search in Rotated Sorted Array)