`

Leetcode - Maximum Gap

    博客分类:
  • Sort
 
阅读更多
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.

[分析]
直接的思路是调用Arrays.sort排序数组,然后依次比较相邻元素,求出最大gap,但Arrays.sort使用快速排序,时间复杂度是O(nlogn),不满足题目要求。 那么线性排序算法有哪些呢?计数排序、基数排序、桶排序,此题可用桶排序解决。
Leetcode的参考解法思路如下:
Suppose there are N elements and they range from A to B.
Then the maximum gap will be no smaller than ceiling[(B - A) / (N - 1)]
Let the length of a bucket to be len = ceiling[(B - A) / (N - 1)], then we will have at most num = (B - A) / len + 1 of bucket.
For any number K in the array, we can easily find out which bucket it belongs by calculating loc = (K - A) / len and therefore maintain the maximum and minimum elements in each bucket.
Since the maximum difference between elements in the same buckets will be at most len - 1, so the final answer will not be taken from two elements in the same buckets.
For each non-empty buckets p, find the next non-empty buckets q, then q.min - p.max could be the potential answer to the question. Return the maximum of all those values.

style2是自己第二次写的实现,注意:
1)仅有两个数时直接返回差值的绝对值
2)min 和 max 相等时可直接返回
3)桶的长度不超过ceil((max - min) / (n - 1))时就无需比较桶内的gap.
桶的个数取 n 而不是 n - 1,考虑case [100, 1,2,3] 此时min + (n - 1) * minGap = max, 等号正好成立,若桶取 n - 1该case会在运行时数组越界。

[ref]
http://blog.csdn.net/u012162613/article/details/41936569

// style 2
public class Solution {
    public int maximumGap(int[] nums) {
        if (nums == null || nums.length < 2)
            return 0;
        if (nums.length == 2) // edge case 1
            return Math.abs(nums[1] - nums[0]);
        // find min and max in nums[]
        int min = Integer.MAX_VALUE, max = Integer.MIN_VALUE;
        for (int a : nums) {
            min = Math.min(min, a);
            max = Math.max(max, a);
        }
        if (min == max) return 0; // edge case 2
        // calculate bucket width
        int n = nums.length;
        // int bucketWidth = (int)Math.ceil((double)(max - min) / (n - 1)); // use n buckets,
        int bucketWidth = (int)Math.ceil((double)(max - min) / (n - 1));
        // init buckets
        int[] minInBucket = new int[n];
        int[] maxInBucket = new int[n];
        Arrays.fill(minInBucket, Integer.MAX_VALUE);
        Arrays.fill(maxInBucket, Integer.MIN_VALUE);
        // populate nums into correct bucket
        for (int a : nums) {
            int idx = (a - min) / bucketWidth;
            minInBucket[idx] = Math.min(minInBucket[idx], a);
            maxInBucket[idx] = Math.max(maxInBucket[idx], a);
        }
        // search the max inter bucket gap
        int maxGap = 0;
        int prev = maxInBucket[0];
        for (int i = 1; i < n; i++) {
            if (minInBucket[i] == Integer.MAX_VALUE) continue;
            maxGap = Math.max(maxGap, minInBucket[i] - prev);
            prev = maxInBucket[i];
        }
        return maxGap;
    }
}


// style 1
public class Solution {
    // http://blog.csdn.net/u012162613/article/details/41936569
    public int maximumGap(int[] nums) {
        if (nums == null || nums.length < 2)
            return 0;
        // find the max & min of the nums
        int max = nums[0], min = nums[0];
        for (int num : nums) {
            if (num > max) max = num;
            if (num < min) min = num;
        }
        // calculate bucket info
        int N = nums.length;
        int bucketLen = (max - min) / (N - 1) + 1;
        int bucketNum = (max - min) / bucketLen + 1;
        int[][] buckets = new int[bucketNum][2];
        boolean[] bucketNonEmpty = new boolean[bucketNum];
        // update num in bucket, each bucket only contains max & min of number belong to this bucket
        for (int num : nums) {
            int bucketId = (num - min) / bucketLen;
            if (bucketNonEmpty[bucketId]) {
                if (num > buckets[bucketId][1]) buckets[bucketId][1] = num;
                if (num < buckets[bucketId][0]) buckets[bucketId][0] = num;
            } else {
                bucketNonEmpty[bucketId] = true;
                buckets[bucketId][0] = num;
                buckets[bucketId][1] = num;
            }
        }
        // calculate max gap
        int maxGap = buckets[0][1] - buckets[0][0];
        int prev = 0;
        for (int i = 1; i < bucketNum; i++) {
            if (bucketNonEmpty[i]) {
                maxGap = Math.max(maxGap, buckets[i][0] - buckets[prev][1]);
                prev = i;
            }
        }
        return maxGap;
    }
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics