python求解LeetCode习题Maximum Gap

来源:互联网 发布:tensorflow feed 图像 编辑:程序博客网 时间:2024/06/08 20:01

题目

Given an unsorted array, find the maximum difference between the successive elements in its sorted form.

Try to solve it in linear time/space.

Return 0 if the array contains less than 2 elements.

You may assume all elements in the array are non-negative integers and fit in the 32-bit signed integer range.

翻译

给定一个无需数组,排序后输出相邻元素的最大差值

思路:

直接排序后,开始遍历数组,记录一个临时变量作为相邻元素的差值,随着遍历的进行更新temp直至遍历结束

具体实现如下:


#!usr/bin/env python#encoding:utf-8'''__Author__:沂水寒城功能:Maximum Gap'''def find_sort_margin(num_list):    '''    给定一个未排序的数组,返回其排序后的数组中 相邻元素之差 最大的值    '''    num_list.sort()    print '有序数组为:', num_list    temp=0    for i in range(len(num_list)-1):        j=i+1        value=num_list[j]-num_list[i]        if value>temp:            temp=value    print '相邻元素之差 最大的值为:', tempif __name__ == '__main__':    num_list=[1,6,12,45,3,89,5,3,0,34]    find_sort_margin(num_list)


结果如下:


有序数组为: [0, 1, 3, 3, 5, 6, 12, 34, 45, 89]相邻元素之差 最大的值为: 44[Finished in 0.3s]



原创粉丝点击