LeetCode(164)Maximum Gap

来源:互联网 发布:深圳最好的java培训 编辑:程序博客网 时间:2024/05/22 16:01

题目

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.

分析

题意为,给定一组无序整数序列,求其有序形式下相邻元素的最大差值;

要求,时空复杂度均为线性。

开始还以为题意理解错了,尝试做了一下,利用库排序函数sort排序,然后一次遍历求得最大差值;时间复杂度为O(nlogn),空间复杂度为O(1);没想到AC了;

看来,题目要求如上描述很简单,考察的关键在于能否实现线性的优化也就延伸为排序算法的线性优化;
参考了别人的桶排序实现代码 ^||^… 羞愧的附上~~~

AC代码

class Solution {public:    //方法一:STL库函数Sort排序,T(n)=O(nlogn)    int maximumGap1(vector<int>& nums) {        if (nums.empty() || nums.size() < 2)            return 0;        int len = nums.size();        sort(nums.begin(), nums.end());        int gap = 0;        for (int i = 1; i < len; ++i)        {            if (nums[i] - nums[i - 1] > gap)                gap = nums[i] - nums[i - 1];        }//for        return gap;    }    //方法二:桶排序    int maximumGap(vector<int>& nums) {        if (nums.empty() || nums.size() < 2)            return 0;        int n = nums.size();        int minAll = *min_element(nums.begin(), nums.end());        int maxAll = *max_element(nums.begin(), nums.end());        // type conversion!!!        double gap = ((double)(maxAll - minAll)) / (n - 1);        // compute min and max element for each bucket        vector<int> minV(n - 1, INT_MAX);        vector<int> maxV(n - 1, INT_MIN);        for (int i = 0; i < n; i++)        {            if (nums[i] != maxAll)            {// the bktId of maxAll will fall out of bucket range                int bktId = (int)((nums[i] - minAll) / gap);                minV[bktId] = min(minV[bktId], nums[i]);                maxV[bktId] = max(maxV[bktId], nums[i]);            }        }        int ret = 0;        int curMax = maxV[0];        for (int i = 1; i < n - 1; i++)        {            if (minV[i] != INT_MAX)            {                ret = max(ret, minV[i] - curMax);                curMax = maxV[i];            }        }        ret = max(ret, maxAll - curMax);        return ret;    }};

GitHub测试程序源码

0 0
原创粉丝点击