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]
阅读全文
0 0
- python求解LeetCode习题Maximum Gap
- leetcode-Maximum Gap
- [LeetCode] Maximum Gap
- LeetCode Maximum Gap
- [leetCode] Maximum Gap
- leetcode 155: Maximum Gap
- LeetCode(164) Maximum Gap
- [LeetCode] Maximum Gap
- [leetcode 164] Maximum Gap
- [leetcode]Maximum Gap
- LeetCode - Maximum Gap 题解
- Maximum Gap|leetcode题解
- LeetCode[Sort]: Maximum Gap
- [LeetCode] Maximum Gap
- leetcode maximum gap
- [LeetCode]Maximum Gap
- LeetCode OJ Maximum Gap
- LeetCode Maximum Gap
- 2-1 Zabbix Service支持JMX监控的安装及配置
- Java redis操作api之redisson
- 面经
- 115个Java面试题和答案——终极列表(上)
- 用MySQL实现准实时推荐
- python求解LeetCode习题Maximum Gap
- boost 处理命令行选项参数
- HDU-2577-How to Type(模拟)
- 服务治理
- 第9章 Java中的线程池 ThreadPoolExecutor
- vmalloc 实现
- OTA升级
- PAT(Basic Level)_1001_害死人不偿命的(3n+1)猜想
- Linux 文件系统管理---分区介绍