【leetcode 桶排序】Maximum Gap,leetcodemaximum

來源:互聯網
上載者:User

【leetcode 桶排序】Maximum Gap,leetcodemaximum
1、題目

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.


2、分析

題意:給定一個未排序的數組,返回其排序後的數組中 相鄰元素之差 最大的值。

比如給定:[5,9,8,3,15]

排序後為:[3,5,8,9,15],相鄰元素之差最大的是15-9=6,返回6。

複雜度要求:時間空間均為O(n)。


這道題最直接的解法是,先排序,得到有序數組,然後再對相鄰元素作差,找出差最大的,比如下面簡短的代碼:

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

在Leetcode上上面的代碼可以AC,但事實上並沒有滿足時間複雜度要求。因為STL函數sort()的複雜度是O(nlogn),【sort C++ reference】。


那麼,線性排序演算法有哪些?計數排序、基數排序、桶排序。

下面用桶排序實現,這也是leetcode上給出的參考解法,我直接copy過來:


Suppose there are N elements and they range from A to B.

Then the maximum gap will be no smaller than ceiling[(B - A) / (N - 1)]

Let the length of a bucket to be len = ceiling[(B - A) / (N - 1)], then we will have at most num = (B - A) / len + 1 of bucket

for any number K in the array, we can easily find out which bucket it belongs by calculating loc = (K - A) / len and therefore maintain the maximum and minimum elements in each bucket.

Since the maximum difference between elements in the same buckets will be at most len - 1, so the final answer will not be taken from two elements in the same buckets.

For each non-empty buckets p, find the next non-empty buckets q, then q.min - p.max could be the potential answer to the question. Return the maximum of all those values.

根據上面的思路,得到代碼如下:

class Solution {public:    int maximumGap(vector<int> &num) {       if (num.size() < 2) return 0;        //遍曆一遍,找出最大最小值        int maxNum = num[0];        int minNum = num[0];        for (int i : num) {            maxNum=max(maxNum,i);            minNum=min(minNum,i);        }        // 每個桶的長度len,向上取整所以加+        int len = (maxNum - minNum) / num.size() + 1;                //桶的個數:(maxNum - minNum) / len + 1,每個桶裡面儲存屬於該桶的最大值和最小值即可,注意這裡的最大最小值是局部的        vector<vector<int>> buckets((maxNum - minNum) / len + 1);        for (int x : num) {            int i = (x - minNum) / len;            if (buckets[i].empty()) {                buckets[i].reserve(2);                buckets[i].push_back(x);                buckets[i].push_back(x);            } else {                if (x < buckets[i][0]) buckets[i][0] = x;                if (x > buckets[i][1]) buckets[i][1] = x;            }        }        //gap的計算,For each non-empty buckets p, find the next non-empty buckets q, return min( q.min - p.max )        int gap = 0;        int prev = 0;        for (int i = 1; i < buckets.size(); i++) {            if (buckets[i].empty()) continue;            gap = max(gap, buckets[i][0] - buckets[prev][1]);            prev = i;        }        return gap;    }};



【其他解法以後再更新】


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.