zoukankan      html  css  js  c++  java
  • Maximum Gap (ARRAY SORT)

    QUESTION

    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.

    1ST TRY

    桶排序

    class Solution {
    public:
        int maximumGap(vector<int> &num) {
            if(num.empty() || num.size() < 2)
                return 0;
            int maxNum = *max_element(num.begin(), num.end());
            int minNum = *min_element(num.begin(), num.end());
            
            //bucket gap: 假设每个数一个桶,两个桶之间的平均差值
            int gap = ceil((double)(maxNum - minNum)/(num.size()-1));
            //number of buckets
            int bucketNum = (maxNum-minNum)/gap+1;
            //declare buckets
            vector<int> bucketsMin(bucketNum, INT_MAX);
            vector<int> bucketsMax(bucketNum, INT_MIN);
            //put into buckets
            for(int i = 0; i < num.size(); i ++)
            {
                int buckInd = (num[i]-minNum)/gap; //匹配到bucket
                bucketsMin[buckInd] = min(bucketsMin[buckInd], num[i]);
                bucketsMax[buckInd] = max(bucketsMax[buckInd], num[i]);
            }
            
            //i_th gap is minvalue in i+1_th bucket minus maxvalue in i_th bucket 
            int maxGap = INT_MIN;
            int previous = minNum;
            for(int i = 0; i < bucketNum; i ++)
            {
                if(bucketsMin[i] == INT_MAX && bucketsMax[i] == INT_MIN)
                    continue;   //empty
                maxGap = max(maxGap, bucketsMin[i]-previous);
                previous = bucketsMax[i];
            }
            return maxGap;
        }
    };

    Result: Accepted

  • 相关阅读:
    TCP三次握手和四次挥手详解
    Core Bluetooth Programming Guide
    iBeacon
    Xcode6:The file couldn’t be opened because you don’t have permission to view it
    关于IOS的蓝牙(转)
    iPad accessory communication through UART
    关于蓝牙设备与ios连接后,自动打开一个app
    Protocol
    闪屏效果
    修改avd路径
  • 原文地址:https://www.cnblogs.com/qionglouyuyu/p/4166260.html
Copyright © 2011-2022 走看看