用python写算法3[旋转链表]

题目:把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。输入一个排好序的数组的一个旋转,输出旋转数组的最小元素。例如数组{3, 4, 5, 1, 2}{1, 2, 3, 4, 5}的一个旋转,该数组的最小值为1

解答:

#!/usr/bin/python
#coding=gbk

'''
Created on 2013-03-25
@author: songjian
'''

def get_min(test_arr):
    low_index = 0
    high_index = len(test_arr) - 1
    mid_index = low_index

    while test_arr[low_index] >= test_arr[high_index]:
        if low_index + 1 == high_index:
            mid_index = high_index
            break

        mid_index = (low_index + high_index) / 2

        if test_arr[mid_index] == test_arr[low_index] and \
           test_arr[mid_index] == test_arr[high_index]:
           return find_min_sequence(test_arr, low_index, high_index)
        elif test_arr[mid_index] >= test_arr[low_index]:
            low_index = mid_index
        elif test_arr[mid_index] <= test_arr[high_index]:
            high_index = mid_index
        else:
            pass

    return test_arr[mid_index]

def find_min_sequence(test_arr, low, high):
    min = test_arr[low]
    for i in range(low, high):
        if test_arr[i] < min:
            min = test_arr[i]

    return min

def main():
    # test_case = [3, 4, 5, 1, 2]
    test_case = [1, 0, 1, 1, 1]
    print get_min(test_case)

if __name__ == '__main__':
    main()

 

 

posted on 2013-03-26 09:34  jiyiyouxin  阅读(180)  评论(0)    收藏  举报