Maximum Gap
Question: http://www.lintcode.com/en/problem/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. Sort is easy but will cost O(nlogn) time. Try to solve it in linear time and space. Answer: class Solution { public: int maximumGap(vector<int> &num) { if (num.size() < 2) return 0; int maxNum = num[0]; int minNum = num[0]; for (int x : num) { maxNum = max(maxNum, x); minNum = min(minNum, x); } int len = (maxNum - minNum) / num.size() + 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); ...