Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to search and rotate sorted array by python

Shulou Source: shulou.com Published: 2022-05-31 14:12:02 09月24日 Update

This article mainly explains "python how to achieve search rotation sort array", the article explains the content is simple and clear, easy to learn and understand, the following please follow the editor's ideas slowly in depth, together to study and learn "python how to search rotation sort array" bar!

[title]

Suppose that an array sorted in ascending order is rotated at a pre-unknown point.

(for example, an array [0meme1reparent2magor455pyrr7] may become [4pyrrine 5rec 6pr 7jor0rec 1reie2]).

Searches for a given target value, and returns its index if it exists in the array, otherwise-1.

You can assume that there are no duplicate elements in the array.

The time complexity of your algorithm must be O (log n).

Example 1:

Input: nums = [4, 5, 5, 6, 7, 0, 1, 2], target = 0

Output: 4

Example 2:

Input: nums = [4, 5, 5, 6, 7, 0, 1, 2], target = 3

Output:-1

[ideas]

1. Brute force solution: for loop to find the target value.

2. Look for special deformation in dichotomy. It must be understood that no matter how it rotates, there is always a part of the interval in order. For example, at least one of l-> mid and mid- > r is ordered. Our logic is to determine whether target is in an ordered interval, and then move another pointer to the ordered interval, otherwise the pointer of the ordered interval (another boundary pointer except mid) is moved outside the ordered interval.

[code]

Python version

Class Solution:

Def search (self, nums: List [int], target: int)-> int:

L, r = 0, len (nums)-1

While l r is orderly.

If nums [mid] < nums [r]:

If nums [mid] < target mid is ordered

Else:

If nums [l]

Tags: Arrays ordering sorting search intervals pointers goals target values learning content that is ideas examples movement input output complex special medium code Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno vpn Redmi Xiaomi MySQL macOS