Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to search and rotate sorted array by python

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)05/31 Report--

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]

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report