zoukankan      html  css  js  c++  java
  • LeetCode(164)Maximum Gap

    题目

    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测试程序源码

  • 相关阅读:
    【Python3爬虫】一次应对JS反调试的记录
    【Python3爬虫】突破反爬之应对前端反调试手段
    学习CSS之如何改变CSS伪元素的样式
    学习CSS之用CSS实现时钟效果
    学习CSS之用CSS绘制一些基本图形
    【Python3爬虫】一次破解JS加密数据的记录
    Linux安装部署Redis(超级详细)
    Linux部署MongoDB
    使用Nginx对.NetCore站点进行反向代理
    Linux部署.NetCore站点 使用Supervisor进行托管部署
  • 原文地址:https://www.cnblogs.com/shine-yr/p/5214725.html
Copyright © 2011-2022 走看看