LeetCode Maximum Gap,leetcodemaximum

來源:互聯網
上載者:User

LeetCode Maximum Gap,leetcodemaximum

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.

Credits:
Special thanks to @porker2008 for adding this problem and creating all test cases.

Show TagsHave you met this question in a real interview? Yes No

Discuss

題目大意:

給定一個未排序的數組,找出其排序後的序列中兩個相鄰元素之間的最大差值。

最好線上性時間、線性空間複雜度內完成。

如果數組少於2個元素,返回0

可以假設數組中的所有元素均為非負整數,並且在32位帶正負號的整數的範圍以內。

解題思路:

基數排序(radix sort)/桶排序(bucket sort)

官方版(桶排序):

假設有N個元素A到B。

那麼最大差值不會大於ceiling[(B - A) / (N - 1)]

令bucket(桶)的大小len = ceiling[(B - A) / (N - 1)],則最多會有(B - A) / len + 1個桶

對於數組中的任意整數K,很容易通過算式loc = (K - A) / len找出其桶的位置,然後維護每一個桶的最大值和最小值

由於同一個桶內的元素之間的差值至多為len - 1,因此最終答案不會從同一個桶中選擇。

對於每一個非空的桶p,找出下一個非空的桶q,則q.min - p.max可能就是備選答案。返回所有這些可能值中的最大值。


class Solution {public:int maximumGap(vector<int> &num) { if (num.empty() || num.size() < 2)return 0;int Max = *max_element(num.begin(), num.end());int Min = *min_element(num.begin(), num.end());int gap = (int)ceil((double)(Max-Min)/(num.size() - 1));int bucketNum = (int) ceil((double)(Max-Min)/gap);vector<int> bucketsMin(bucketNum, INT_MAX);vector<int> bucketsMax(bucketNum, INT_MIN);for (int i = 0; i < num.size(); i++) {if (num[i] == Max || num[i] == Min)continue;int idx = (num[i] - Min) / gap;bucketsMin[idx] = min(bucketsMin[idx], num[i]);bucketsMax[idx] = max(bucketsMax[idx], num[i]);}int ans = INT_MIN;int previous = Min;for (int i = 0; i < bucketNum; i++) {if (bucketsMin[i] == INT_MAX || bucketsMax[i] == INT_MIN) continue;ans = max(ans, bucketsMin[i] - previous);previous = bucketsMax[i];}ans = max(ans, Max - previous);return ans;}};


聯繫我們

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