编写一个函数,以确定原始排序列表被旋转以获取给定列表的最小次数。我的代码怎么了?
示例:通过旋转排序列表[0、2、3、4、5、6、9] 3次获得列表[5、6、9、0、2、3、4]。
这是我的代码 -
def count_rotations_binary(nums):
lo = 0
hi = len(nums)-1
while lo <= hi:
mid = (lo+hi)//2
mid_number = nums[mid]
print("lo:", lo, ", hi:", hi, ", mid:", mid, ", mid_number:", mid_number)
if mid > 0 and nums[mid] < nums[mid-1] :
# The middle position is the answer
return mid
elif nums[mid] < nums[len(nums)-1] :
# Answer lies in the left half
hi = mid - 1
else:
# Answer lies in the right half
lo = mid + 1
return 0
q = count_rotations_binary([9,10,11,1,4,6,7,8])
print(q)
Example: The list [5, 6, 9, 0, 2, 3, 4] was obtained by rotating the sorted list [0, 2, 3, 4, 5, 6, 9] 3 times.
here is my code -
def count_rotations_binary(nums):
lo = 0
hi = len(nums)-1
while lo <= hi:
mid = (lo+hi)//2
mid_number = nums[mid]
print("lo:", lo, ", hi:", hi, ", mid:", mid, ", mid_number:", mid_number)
if mid > 0 and nums[mid] < nums[mid-1] :
# The middle position is the answer
return mid
elif nums[mid] < nums[len(nums)-1] :
# Answer lies in the left half
hi = mid - 1
else:
# Answer lies in the right half
lo = mid + 1
return 0
q = count_rotations_binary([9,10,11,1,4,6,7,8])
print(q)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论