【桶排序】MAXIMUM GAP
2015-03-06 10:15
453 查看
题目: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的来源只有一种可能:两个相邻非空的桶之间,“大桶最小值”减去“小桶最大值”之差。
若输入的数组中所有元素都相等时,程序返回0。
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的来源只有一种可能:两个相邻非空的桶之间,“大桶最小值”减去“小桶最大值”之差。
若输入的数组中所有元素都相等时,程序返回0。
//返回值第一个是数组最小值,第二个数是数组最大值 pair<int, int> minmax(const vector<int> &s) { if (s.size()==1) return make_pair(s[0], s[0]); 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; } //把数组s的元素平均分成s.size()组,每组前闭后开,即类似 [a,b) vector<vector<int>> bucketsort(const vector<int> &s, const int size) { pair<int, int> r = minmax(s); double interval = r.second - r.first; interval /= size - 1; vector<vector<int>> bucket(size); for (size_t i = 0; i < s.size(); i++) { double temp=(s[i] - r.first) / interval; int index = temp; 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()); //bucket[0]肯定非空,因为里面有最小值 pair<int, int> r = minmax(bucket[0]); //把gap初始化为0,当输入的数组中所有元素都相等时,返回0 int gap = 0, premax = r.second; for (size_t i =1; i < bucket.size(); i++) { if (bucket[i].empty()) continue; pair<int, int> t = minmax(bucket[i]); gap = max(gap,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"; }
相关文章推荐
- [leetcode][桶排序] Maximum Gap
- 【leetcode 桶排序】Maximum Gap
- 桶排序和直接排序的数据结构和算法2
- 桶排序的实现
- 漫谈经典排序算法:五、线性时间排序(计数、基数、桶排序)
- 《算法导论》CLRS算法C++实现(七)P102 桶排序
- 桶排序
- 桶排序
- 【算法学习】线性时间排序-计数排序、基数排序和桶排序详解与编程实现
- 桶排序
- 桶排序 一个有点小巧的排序算法
- 各种线性排序记录(计数排序,基数排序,桶排序) 及 希尔排序
- 桶排序
- 桶排序(Bucket Sort)
- 桶排序
- 桶排序--小试牛刀
- 三种线性的非基于比较的排序算法:计数排序、桶排序与基数排序
- 桶排序
- 桶排序
- Maximum Gap