美文网首页Leetcode每日两题
Leetcode 164. Maximum Gap

Leetcode 164. Maximum Gap

作者: ShutLove | 来源:发表于2017-11-06 20:35 被阅读13次

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;
}

相关文章

  • 2019-01-16

    LeetCode 164. Maximum Gap Description Given an unsorted a...

  • Leetcode 164. Maximum Gap

    Given an unsorted array, find the maximum difference betw...

  • LeetCode 164. Maximum Gap

    Description Given an unsorted array, find the maximum dif...

  • ARTS 第20周

    ARTS 第20周分享 [TOC] Algorithm 164. Maximum Gap [hard] [题目描述...

  • 164. Maximum Gap

    问题描述 Given an unsorted array, find the maximum difference...

  • Leetcode - Maximum Gap

    My code: 看到这道题目,第一个想法是排序。然后要求排序时间复杂度是 O(n)就想到了 radix sort...

  • Maximum Gap

    https://leetcode.com/problems/maximum-gap/给定一个无序int数组,求出排...

  • 164. Maximum Gap(最大间距)

    题目 LeetCode中文站 解答 根据题意我们就可以直到这是一题先排序,然后再寻找最大间距的题目,我们先使用最简...

  • Leetcode-164-Maximum Gap

    给定一个未排序的数组,求排序后数组中相邻元素之差的最大值。 这题最大的思维盲点就在于的复杂度让人直接放弃包含排序的...

  • 4.5 leet 53|70|83

    Maximum Subarrayhttps://leetcode.com/problems/maximum-sub...

网友评论

    本文标题:Leetcode 164. Maximum Gap

    本文链接:https://www.haomeiwen.com/subject/ebkrmxtx.html