博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python leetcode 164. Maximum Gap
阅读量:3534 次
发布时间:2019-05-20

本文共 1645 字,大约阅读时间需要 5 分钟。

O(N)的复杂度,运用桶排序(代码1)。但是取巧的方法(代码2)居然24ms,100%。应该是测试数据集设置得不好

class Solution():    def maximumGap(self, nums):        """        :type nums: List[int]        :rtype: int        """        import math        if len(nums) <= 1 :            return 0                        minValue = 2**31-1        maxValue = -2**31        for num in nums:            minValue = min(minValue, num)            maxValue = max(maxValue, num)                        bucket_range = (maxValue - minValue) / len(nums) + 1        bucket_num = math.ceil((maxValue - minValue) / bucket_range) + 1                hashmapMax = {
} hashmapMin = {
} for i in range(len(nums)): bucket_id = (nums[i]-minValue) // bucket_range if not bucket_id in hashmapMax: hashmapMax[bucket_id] = nums[i] hashmapMin[bucket_id] = nums[i] else: hashmapMax[bucket_id] = max(hashmapMax[bucket_id],nums[i]) hashmapMin[bucket_id] = min(hashmapMin[bucket_id],nums[i]) prev = 0 res = 0 for i in range(1,bucket_num): if not i in hashmapMax: continue if not prev in hashmapMax: continue res = max(res, hashmapMin[i] - hashmapMax[prev]) prev = i return res
class Solution(object):    def maximumGap(self, nums):        """        :type nums: List[int]        :rtype: int        """        ln=len(nums)        if ln<2:            return 0         nums.sort()        res=0        for i in range(ln-1):            res=max(res,nums[i+1]-nums[i])        return res

转载地址:http://zwahj.baihongyu.com/

你可能感兴趣的文章
惰性求值,面向对象
查看>>
lodash源码分析之baseSlice()函数
查看>>
数据结构之列表
查看>>
发布/订阅模式 vs 观察者模式
查看>>
es5中的arguments对象
查看>>
git本地仓库和远程仓库关联,分支重命名
查看>>
js对象的深拷贝,你真的觉得很简单吗?
查看>>
你真的了解map方法吗?手动实现数组map方法。
查看>>
带你手动实现call方法,让你收获满满
查看>>
前端知识体系
查看>>
查找入职员工时间排名倒数第三的员工所有信息
查看>>
使用join查询方式找出没有分类的电影id以及名称
查看>>
Qt教程(2) : Qt元对象系统
查看>>
驱动开发误用指针错误:Unable to handle kernel NULL pointer dereference at virtual address
查看>>
Linux部署DocSystem知识/文件管理系统
查看>>
Centos7开机自启动脚本无法使用备用方案
查看>>
jvm虚拟机内存详解
查看>>
线程的创建方式
查看>>
DNS是什么
查看>>
mapreduce自定义分组、自定义分区、二次排序
查看>>