C++實現LeetCode(164.求最大間距)
[LeetCode] 164. Maximum Gap 求最大間距
Given an unsorted array, find the maximum difference between the successive elements in its sorted form.
Return 0 if the array contains less than 2 elements.
Example 1:
Input: [3,6,9,1]
Output: 3
Explanation: The sorted form of the array is [1,3,6,9], either
(3,6) or (6,9) has the maximum difference 3.
Example 2:
Input: [10]
Output: 0
Explanation: The array contains less than 2 elements, therefore return 0.
Note:
- You may assume all elements in the array are non-negative integers and fit in the 32-bit signed integer range.
- Try to solve it in linear time/space.
遇到這類問題肯定先想到的是要給數組排序,但是題目要求是要線性的時間和空間,那麼隻能用桶排序或者基排序。這裡用桶排序 Bucket Sort 來做,首先找出數組的最大值和最小值,然後要確定每個桶的容量,即為 (最大值 – 最小值) / 個數 + 1,在確定桶的個數,即為 (最大值 – 最小值) / 桶的容量 + 1,然後需要在每個桶中找出局部最大值和最小值,而最大間距的兩個數不會在同一個桶中,而是一個桶的最小值和另一個桶的最大值之間的間距,這是因為所有的數字要盡量平均分配到每個桶中,而不是都擁擠在一個桶中,這樣保證瞭最大值和最小值一定不會在同一個桶中,具體的證明博主也不會,隻是覺得這樣想挺有道理的,各位看官大神們若知道如何證明請務必留言告訴博主啊,參見代碼如下:
class Solution { public: int maximumGap(vector<int>& nums) { if (nums.size() <= 1) return 0; int mx = INT_MIN, mn = INT_MAX, n = nums.size(), pre = 0, res = 0; for (int num : nums) { mx = max(mx, num); mn = min(mn, num); } int size = (mx - mn) / n + 1, cnt = (mx - mn) / size + 1; vector<int> bucket_min(cnt, INT_MAX), bucket_max(cnt, INT_MIN); for (int num : nums) { int idx = (num - mn) / size; bucket_min[idx] = min(bucket_min[idx], num); bucket_max[idx] = max(bucket_max[idx], num); } for (int i = 1; i < cnt; ++i) { if (bucket_min[i] == INT_MAX || bucket_max[i] == INT_MIN) continue; res = max(res, bucket_min[i] - bucket_max[pre]); pre = i; } return res; } };
Github 同步地址:
https://github.com/grandyang/leetcode/issues/164
參考資料:
https://leetcode.com/problems/maximum-gap
http://blog.csdn.net/u011345136/article/details/41963051
https://leetcode.com/problems/maximum-gap/discuss/50642/radix-sort-solution-in-java-with-explanation
https://leetcode.com/problems/maximum-gap/discuss/50643/bucket-sort-java-solution-with-explanation-on-time-and-space
到此這篇關於C++實現LeetCode(164.求最大間距)的文章就介紹到這瞭,更多相關C++實現求最大間距內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!
推薦閱讀:
- C++實現LeetCode(152.求最大子數組乘積)
- C++實現LeetCode(347.前K個高頻元素)
- C++實現LeetCode(228.總結區間)
- C++實現LeetCode(153.尋找旋轉有序數組的最小值)
- C++實現LeetCode(154.尋找旋轉有序數組的最小值之二)