"Leetcode" 33-search in rotated Sorted Array [Python]__python

Source: Internet
Author: User

Suppose a sorted array is rotated in some pivot unknown to your beforehand.

(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).

You are 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.


Meaning

Suppose an array of rows reverses at one node

(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).

Given a target value, if there is this value in the array, returns its subscript, if not, returns-1

You can assume that there are no duplicates in the array


Ideas:

The binary method is to determine the ascending sequence in which the median value belongs, and then continue to judge whether the target should fall to the left or right region based on the endpoint value.


Python:

Class Solution (object):
    def search (self, nums, target): "
        "
        : Type Nums:list[int]
        : Type Target:int
        : Rtype:int
        "" "
        
        start=0
        End=len (nums)-1 while
        
        start<=end:
        
            mid= (start+end)/2
        
            if Nums[mid]==target: Return
                mid
                
            if Nums[mid]>=nums[start]:                              #当nums [mid] is part of the left ascending sequence if
        
                target >=nums[start] and Target<nums[mid]:
                    end=mid-1
                Else:
                    start=mid+1
            
            if nums[mid]<nums[ end]:                                 #当nums [mid] to the right ascending sequence
        
                if Target>nums[mid] and Target<=nums[end]:
                    start=mid+1
                Else:
                    end=mid-1
                
        return-1


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.