imnotEnvy
11/29/2017 - 10:03 AM

找到旋转的已排序数组的乱序点

func([5, 6, 1, 2, 3, 4]) => 1 func([3, 4, 5, 1, 2]) => 2

def find_pivot(arr):
    low = 0
    high = len(arr) - 1
    while low < high:
        mid = (low + high) // 2
        if arr[mid] > arr[mid + 1]:
            return mid
        if arr[mid] < arr[mid - 1]:
            return mid - 1
        if arr[low] >= arr[mid]:
            high = mid - 1
        else:
            low = mid + 1
    return -1


def binary_search(arr, item):
    low = 0
    high = len(arr)

    while low <= high:
        mid = (low + high) // 2
        if arr[mid] == item:
            return mid
        elif arr[mid] < item:
            low = mid + 1
        else:
            high = mid - 1
    return -1