Maximum Gap -- leetcode

來源:互聯網
上載者:User

標籤:leetcode   gap   bucket   桶   

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.



基本思路:

先求出無序數組中的最大值和最小值。

當每個數,都等距離分布時,此時將取得max gap的下限值。

span = ceiling[(B - A) / (N - 1)]

其中,B為最小值,A為最大值,N為元素個數

如果以此span作為一個桶的取值範圍。 並將數分配進這些桶內。

那麼在同一個桶內的數,之間的有序gap,將不會超過span。則桶內的數的,彼此之間就不用再求gap。

只需要計算桶與桶之間的gap,並保留最大值。

而桶與桶之間的gap,則是後一桶的最小值,與 前一桶的最大值之間的差值。

故在分配時,只需要記住該桶內的最小值,和最大值。


class Solution {public:    int maximumGap(vector<int>& nums) {        if (nums.size() < 2)            return 0;        int minV = nums[0];        int maxV = nums[0];        for (auto i: nums) {            if (i < minV)                minV = i;            else if (i > maxV)                maxV = i;        }                if (maxV == minV)            return 0;                int span = (maxV-minV) / (nums.size()-1);        span = max(1, span);        int buckets_count = (maxV-minV)/span;        ++buckets_count;                vector<int> buckets_min(buckets_count, INT_MAX);        vector<int> buckets_max(buckets_count, INT_MIN);                for (auto i: nums) {            int slot = (i-minV) / span;            buckets_min[slot] = min(buckets_min[slot], i);            buckets_max[slot] = max(buckets_max[slot], i);        }                int gap = 0;        int last_max = buckets_max[0];        for (int i=1; i<buckets_count; i++) {            if (buckets_max[i] != INT_MIN) {                gap = max(gap, buckets_min[i]-last_max);                last_max = buckets_max[i];            }        }        return gap;    }};



Maximum Gap -- leetcode

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.