Leetcode 164. Maximum Gap

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.

思路:
找到最小的bucketSize,生成buckets,把每个num放到对应bucket中,同时更新这个bucket的最大值和最小值。
遍历buckets,比较相邻bucket的min和max的最大差值,更新maximum。

class Bucket {
    public boolean used = false;
    public int min = Integer.MAX_VALUE;
    public int max = Integer.MIN_VALUE;
}

public int maximumGap(int[] nums) {
    if (nums == null || nums.length <= 1) {
        return 0;
    }

    //n elem, n-1 buckets
    int max = Integer.MIN_VALUE, min = Integer.MAX_VALUE;
    for (int i = 0; i < nums.length; i++) {
        max = Math.max(max, nums[i]);
        min = Math.min(min, nums[i]);
    }

    int bucketSize = (int)Math.ceil((double)(max - min) / (nums.length - 1));;
    if (bucketSize == 0) {
        return 0;
    }

    int bucketNum = (max - min) / bucketSize + 1;
    Bucket[] buckets = new Bucket[bucketNum];
    for (int i = 0; i < buckets.length; i++) {
        buckets[i] = new Bucket();
    }
    // Arrays.fill(buckets, new Bucket());

    for (int num : nums) {
        int bucketIndex = (num - min) / bucketSize;
        buckets[bucketIndex].used = true;
        buckets[bucketIndex].min = Math.min(buckets[bucketIndex].min, num);
        buckets[bucketIndex].max = Math.max(buckets[bucketIndex].max, num);
    }

    int preMax = min, maxGap = 0;
    for (Bucket bucket : buckets) {
        if (!bucket.used) {
            continue;
        }
        maxGap = Math.max(maxGap, bucket.min - preMax);
        preMax = bucket.max;
    }

    return maxGap;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Description Given an unsorted array, find the maximum dif...
    柳正来阅读 722评论 0 0
  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,769评论 0 33
  • 原谅我又去听了网易一个很丧的歌单 歌单里那么多评论 那么多人想死 那么多人抑郁 那么多人嘲讽 “不要把心情差当...
    akimbo阅读 187评论 0 0
  • 坐在竹椅上,轻晃,日头正暖。 放在晴空下,安睡,蓝色小床。 你轻轻地呼吸,我静静地陪伴。 小小的手呀,小小的脚。 ...
    双水罐子阅读 276评论 0 0
  • 曾经的蓝色天空总是一尘不染艳阳高照 即使是阴天下雨的时候我也能感受到炙热的心跳 迎着甜腻的海风 自顾自地鸣...
    脑洞少年阅读 378评论 0 0