[LintCode] Maximum Gap 求最大间距

简介:

Given an unsorted array, find the maximum difference between the successive elements in its sorted form.

Return 0 if the array contains less than 2 elements.

 Notice

You may assume all elements in the array are non-negative integers and fit in the 32-bit signed integer range.

Example

Given [1, 9, 2, 5], the sorted form of it is[1, 2, 5, 9], the maximum gap is between 5and 9 = 4.

Challenge 

Sort is easy but will cost O(nlogn) time. Try to solve it in linear time and space.

LeetCode上的原题,请参见我之前的博客Maximum Gap

class Solution {
public:
    /**
     * @param nums: a vector of integers
     * @return: the maximum difference
     */
    int maximumGap(vector<int> nums) {
        if (nums.empty()) return 0;
        int mx = INT_MIN, mn = INT_MAX, n = nums.size();
        for (int d : nums) {
            mx = max(mx, d);
            mn = min(mn, d);
        }
        int size = (mx - mn) / n + 1;
        int bucket_num = (mx - mn) / size + 1;
        vector<int> bucket_min(bucket_num, INT_MAX);
        vector<int> bucket_max(bucket_num, INT_MIN);
        set<int> s;
        for (int d : nums) {
            int idx = (d - mn) / size;
            bucket_min[idx] = min(bucket_min[idx], d);
            bucket_max[idx] = max(bucket_max[idx], d);
            s.insert(idx);
        }
        int pre = 0, res = 0;
        for (int i = 1; i < n; ++i) {
            if (!s.count(i)) continue;
            res = max(res, bucket_min[i] - bucket_max[pre]);
            pre = i;
        }
        return res;
    }
};

本文转自博客园Grandyang的博客,原文链接:求最大间距[LintCode] Maximum Gap ,如需转载请自行联系原博主。

相关文章
LeetCode 164. Maximum Gap
给定一个无序的数组,找出数组在排序之后,相邻元素之间最大的差值。 如果数组元素个数小于 2,则返回 0。
61 0
LeetCode 164. Maximum Gap
|
Java 数据安全/隐私保护
[LintCode] Number of Islands(岛屿个数)
描述 给一个01矩阵,求不同的岛屿的个数。 0代表海,1代表岛,如果两个1相邻,那么这两个1属于同一个岛。我们只考虑上下左右为相邻。 样例 在矩阵: [ [1, 1, 0, 0, 0], [0, 1, 0, 0, 1], [0, 0, 0, 1, 1], [0, 0, 0, 0, 0], [0, 0, 0, 0, 1] ] 中有 3 个岛。
1235 0