• [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;
        }
    };
  • 相关阅读:
    php -- php数组相关函数
    php -- 数组排序
    php -- in_array函数
    php -- 魔术方法 之 删除属性:__unset()
    无符号整型与有符号整型相运算规则
    N个节点的二叉树有多少种形态
    getopt_long
    typedef
    约瑟夫环问题算法(M)
    C语言基础
  • 原文地址:https://www.cnblogs.com/grandyang/p/5838403.html
Copyright © 2020-2023  润新知