[英]Finding Pivot element in a sorted array, How do I optimize this code?
Is there a way to optimize this code?有没有办法优化这段代码? I'm trying to find an element in the list where the sorted list is rotated.我试图在排序列表旋转的列表中找到一个元素。 [8,9,10,11,12,6,7] Here the element I'm trying to find is 6 with an index 5. [8,9,10,11,12,6,7] 这里我要查找的元素是 6,索引为 5。
class Solution:
def search(self, nums: List[int]) -> int:
lenn = len(nums)-1
pivot, mid = 0, (0 + lenn)//2
if(nums[0] > nums[lenn]):
while True:
if(nums[mid] > nums[mid+1]):
pivot = mid+1
break
if(nums[mid] < nums[mid-1]):
pivot = mid
break
if(nums[mid] > nums[lenn]):
mid += 1
if(nums[mid] < nums[lenn]):
mid -= 1
return pivot
Your solution is fast for small lists but not for big ones as it perform a linear-time search<\/strong> .您的解决方案适用于小型列表,但不适用于大型列表,因为它执行线性时间搜索<\/strong>。 To be faster, you can use a binary search<\/strong> .为了更快,您可以使用二分搜索<\/strong>。 To do that, you need to use a keep a [start;end]<\/code> range of values that contains the "pivot".
为此,您需要使用包含“枢轴”的
[start;end]<\/code>值范围。
You just need to take the middle item and find which part (left or right) contains increasing items.您只需要取出中间的项目,然后找到哪个部分(左侧或右侧)包含增加的项目。
Moreover, you can micro-optimize<\/strong> the code.此外,您可以对代码进行微优化<\/strong>。 The default implementation of Python is CPython which is a slow interpreter. Python 的默认实现是 CPython,它是一个缓慢的解释器。 It optimize almost nothing compared to compilers (of languages like C, Java, Rust) so you should do the optimizations yourself if you want a fast code.与编译器(C、Java、Rust 等语言)相比,它几乎没有优化任何东西,所以如果你想要一个快速的代码,你应该自己进行优化。 The idea is to use a linear search for few items and a binary search for many ones, and to store values in temporary variables not to compute them twice.这个想法是对少数项目使用线性搜索,对许多项目使用二进制搜索,并将值存储在临时变量中,而不是计算两次。
Here is the resulting implementation:这是结果实现:
def search(nums):
first, last = nums[0], nums[-1]
# Trivial case
if first <= last:
return 0
lenn = len(nums)-1
# Micro-optimized fast linear search for few items (optional)
if lenn < 10:
pivot, mid = 0, lenn//2
while True:
middle = nums[mid]
if middle > nums[mid+1]:
return mid+1
elif middle < nums[mid-1]:
return mid
elif middle > last:
mid += 1
elif middle < last:
mid -= 1
# Binary search for many items
start, end = 0, lenn
while start+1 < end:
mid = (start + end) // 2
midVal = nums[mid]
if midVal < nums[start]:
end = mid
elif midVal > nums[end]:
start = mid
else:
assert False
return start+1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.