LeetCode Maximum Gap

class Solution {
public:
    int maximumGap(vector<int> &num) {
        int len = num.size();
        int gap = 0;
        sort(num.begin(), num.end());
        for (int i=0; i<len-1; i++) {
            int cgap = num[i+1] - num[i];
            if (cgap > gap) {
                gap = cgap;
            }
        }
        return gap;
    }
};

等会去看下discuss,找了一个使用基数排序的,发现比快排多了一倍的时间。

第二轮:

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.

只能说自己实现的挫:

#include <iostream>
#include <map>
#include <vector>
#include <cmath>

using namespace std;


class Bucket {
private:
    int min_value;
    int max_value;
    int idx;
    bool isempty;
public:
    Bucket() : min_value(INT_MAX), max_value(INT_MIN) {
        isempty = true;
    }
    void push(int v) {
        if (min_value > v) {
            min_value = v;
        }
        if (max_value < v) {
            max_value = v;
        }
        isempty = false;
    }
    bool empty() {return isempty;}
    int getMax() {return max_value;}
    int getMin() {return min_value;}
    int getIdx() {return idx;}
    void setIdx(int val) {idx = val;}
};

class Solution {
public:
    int maximumGap(vector<int> &num) {
        int n = num.size();

        if (n < 2) {
            return 0;
        }

        int maxv = INT_MIN;
        int minv = INT_MAX;
        for (int e : num) {
            if (e > maxv) {
                maxv = e;
            } else if (e < minv) {
                minv = e;
            }
        }

        int diff = maxv - minv;

        int min_gap = ceil(diff * 1.0 / (n-1));
        int bn = diff / min_gap + 1;

        map<int, Bucket> buckets;

        for (int e : num) {
            int idx = (e - minv) / min_gap;
            if (buckets.count(idx) < 1) {
                buckets[idx] = Bucket();
            }
            buckets[idx].push(e);
        }

        auto iter = buckets.begin();


        Bucket last = iter->second;
        int max_gap = last.getMax() - last.getMin();

        for (iter++;iter!=buckets.end();iter++) {
            int gap = iter->second.getMin() - last.getMax();
            if (gap > max_gap) {
                max_gap = gap;
            }
            gap = iter->second.getMax() - iter->second.getMin();
            if (gap > max_gap) {
                max_gap = gap;
            }
            last = iter->second;
        }
        return max_gap;
    }
};

int main() {
    vector<int> data  ={1,1,1,1,1,5,5,5,5,5};
    
    Solution s;
    int gap = s.maximumGap(data);
    cout<<gap<<endl;
    return 0;
}

 

posted @ 2014-12-21 12:10  卖程序的小歪  阅读(216)  评论(0编辑  收藏  举报