• 边工作边刷题:70天一遍leetcode: day 4


    Maximum Gap

    要点:
    问题:

    • 为什么用n(元素个数)作为bucket的个数?
    • 为什么用range公式

    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.

    
    class Solution(object):
        def maximumGap(self, nums):
            """
            :type nums: List[int]
            :rtype: int
            """
            maxv = -sys.maxint-1
            minv = sys.maxint
            n = len(nums)
            if n==0: return 0
            buckets = [[None, None] for i in range(n)]
            for i in range(n):
                maxv = max(maxv, nums[i])
                minv = min(minv, nums[i])
            
            r = (maxv-minv)/n+1
            for i in range(n):
                bn = (nums[i]-minv)/r
                if not buckets[bn][0] or buckets[bn][0]>nums[i]:
                    buckets[bn][0]=nums[i]
                    
                if not buckets[bn][1] or buckets[bn][1]<nums[i]:
                    buckets[bn][1]=nums[i]
            
            gap = 0
            pre = buckets[0][1]
            for i in range(1, n):
                if buckets[i][0]:
                    gap = max(gap, buckets[i][0]-pre)
                    pre = buckets[i][1]
            
            return gap
    
  • 相关阅读:
    文件操作:Directory,File,FielStream、StreamRead和StreamWriter的使用
    MVC中Excel导入
    T对象序列化后T对象中属性字段不见了?
    Sql游标
    Form表单提交
    AJAX异步删除操作
    数据库表结构导出sql语句
    多线程的使用
    找不到dll原因
    代码优化
  • 原文地址:https://www.cnblogs.com/absolute/p/5554996.html
Copyright © 2020-2023  润新知