题目:leetcode
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.
提示:
假设题目中的排序数组是升序。
运用桶排序,把数组平均分成len组(len是数组元素个数),每组前闭后开,其中最后一组只有一个元素——最大值。
则最大的gap的来源有两种可能:1、每个桶内的最大最小值之差;2、两个相邻非空的桶之间,“大桶最小值”减去“小桶最大值”之差。
//返回值第一个是数组最小值,第二个数是数组最大值 pair<int, int> minmax(const vector<int> &s) { int rmin = INT_MAX, rmax = -1; for (size_t i = 0; i < s.size(); i++) { rmin = min(rmin, s[i]); rmax = max(rmax, s[i]); } pair<int, int> res = { rmin, rmax }; return res; } //求三个数中最大那个数 int maxnum(const int &a, const int &b, const int &c) { int temp = max(a, b); temp = max(temp, c); return temp; } //把数组s的元素平均分成s.size()组,每组前闭后开,即类似 [a,b) vector<vector<int>> bucketsort(const vector<int> &s, const int size) { pair<int, int> r = minmax(s); vector<vector<int>> bucket(size); for (size_t i = 0; i < s.size(); i++) { int index = (s[i] - r.first) / size; bucket[index].push_back(s[i]); } return bucket; } int FindMaxGap(const vector<int> &s) { if (s.size() < 2) return 0; vector<vector<int>> bucket = bucketsort(s,s.size()); int gap, premax; //初始化gap和premax if (bucket[0].size() >= 2) { auto t = minmax(bucket[0]); gap = t.second - t.first; premax = t.second; } else if (bucket[0].empty()) { gap = -1; premax = 0; } else { gap = -1; premax = bucket[0][0]; } for (size_t i = 1; i < bucket.size(); i++) { if (bucket[i].empty()) continue; if (bucket[i].size() == 1) { gap = max(gap, bucket[i][0] - premax); premax = bucket[i][0]; continue; } pair<int, int> t = minmax(bucket[i]); gap = maxnum(gap, t.second - t.first, t.first - premax); premax = t.second; } return gap; } //测试代码 srand((unsigned)time(NULL)); vector<int> n; for (int i = 0; i < 10; i++) { int t = rand() % 100 + 1; n.push_back(t); cout << t << "\t"; } cout << endl; cout << FindMaxGap(n) << endl; sort(n.begin(), n.end()); for (int i = 0; i < 10; i++) { cout << n[i] << "\t"; }
原文地址:http://blog.csdn.net/bupt8846/article/details/44096117