编写一个函数,以确定原始排序列表被旋转以获取给定列表的最小次数。我的代码怎么了?

发布于 2025-02-08 18:53:50 字数 736 浏览 1 评论 0原文

示例:通过旋转排序列表[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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文