[leetcode][桶排序] Maximum Gap
2015-07-02 11:35
369 查看
题目;
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.
分析:平均间隔 =(最大值-最小值)/元素个数; 桶的个数 =(最大值-最小值)/平均间隔。
如果是平均分布,则桶的数目和元素数目相同,则每个桶里有一个数,而若某个桶里有两个以上的数时,则必有至少一个桶是空桶,那么最大间隔可能就落在空桶的两个相邻桶存储的数之间,最大间隔不会落在同一个桶的数之间,因此我们不需要对每个桶内部排序,只需要记录同一个桶的最大值和最小值,算出前一个有最大值的桶的最大值和后一个有最小值的桶的最小值之差,和当前最大间隔比较取得最大间隔。
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.
分析:平均间隔 =(最大值-最小值)/元素个数; 桶的个数 =(最大值-最小值)/平均间隔。
如果是平均分布,则桶的数目和元素数目相同,则每个桶里有一个数,而若某个桶里有两个以上的数时,则必有至少一个桶是空桶,那么最大间隔可能就落在空桶的两个相邻桶存储的数之间,最大间隔不会落在同一个桶的数之间,因此我们不需要对每个桶内部排序,只需要记录同一个桶的最大值和最小值,算出前一个有最大值的桶的最大值和后一个有最小值的桶的最小值之差,和当前最大间隔比较取得最大间隔。
class Solution { public: int maximumGap(vector<int>& nums) {//时间复杂度O(n),空间复杂度O(n) if (nums.size() < 2) return 0; int min = nums[0], max = nums[0]; //找出最大值和最小值 for (int i = 1; i < nums.size(); ++i){ if (nums[i] < min) min = nums[i]; else if (nums[i] > max) max = nums[i]; } int avgGap = ceil((double)(max-min)/nums.size());//平均间隔 int cntBucket = ceil((double)(max - min) / avgGap);//桶的个数 vector<pair<int, int> > buckets(cntBucket, make_pair(INT_MIN, INT_MAX));//桶内的(最大值,最小值) //记录每个桶的最大值和最小值 for (int i = 0; i < nums.size(); ++i){ int numBucket = (nums[i] - min) / avgGap; if (nums[i] > buckets[numBucket].first) buckets[numBucket].first = nums[i];//更新桶内最大值 if (nums[i] < buckets[numBucket].second) buckets[numBucket].second = nums[i];//更新桶内最小值 } //算出最大间隔 int maxGap = 0, lastMax = min; for (int i = 0; i < cntBucket; ++i){ if (buckets[i].first == INT_MIN) continue; if (buckets[i].second - lastMax > maxGap) maxGap = buckets[i].second - lastMax; lastMax = buckets[i].first; } return max - lastMax > maxGap ? max - lastMax : maxGap; } };
相关文章推荐
- 谷歌掐架甲骨文:揭秘Java侵权案始末
- Uva 10891 Game of Sum(区间博弈dp)
- MongoDB Windows环境安装及配置
- BaiduMap---百度地图官方Demo之离线地图功能(介绍如何下载和使用离线地图)
- Practical Advice on Running uClinux on Cortex-M3/M4
- php数组函数
- Xamarin.Android开发实践(四)
- 资讯:爱加密林魏:CTO应该这样做!
- spring mvc拦截器和<mvc:annotation-driven />的详解
- [LeetCode] Kth Smallest Element in a BST
- MySQL分页技术、6种分页方法总结
- Java中只有按值传递,没有按引用传递!
- 我在网页设计中遇到的一些问题以及处理方法整理
- Nginx 配置虚拟机
- php函数操作文件
- SIFT 不完全手册
- 获取视频的第一帧
- WPF Image Binding Uri Source 失败解决办法
- 浅谈 C++ 中的 new/delete 和 new[]/delete[]
- Eclipse: The method of type must override a superclass method解决方式