Maximum Gap——桶排序
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.
代码一(简单易懂版):
桶排序,由于num中的数字肯定在[min,max]区间内,所以根据抽屉原理,假设num中有n个数字,则最大的gap必然要大于dis=(max- min)/(n-1),所以我们可以把num所在的范围分成等间隔的区间,相邻区间内的元素之间的最大差值,即为要寻找的gap。
class Solution {
public:
int maximumGap(vector<int> &num) {
int n = num.size();
if (n < ) return ;
if (n == ) return abs(num[] - num[]);
int imin = num[], imax = num[];
for (int i = ; i < n; ++i) {
imin = min(imin, num[i]);
imax = max(imax, num[i]);
}
int dist = (imax-imin) / n + ;
vector<vector<int> > bucket((imax-imin)/dist + );
int idx;
for (int i = ; i < n; ++i) {
idx = (num[i] - imin) / dist;
if (bucket[idx].empty()) {
bucket[idx].push_back(num[i]);
bucket[idx].push_back(num[i]);
} else {
bucket[idx][] = min(bucket[idx][], num[i]);
bucket[idx][] = max(bucket[idx][], num[i]);
}
}
int gap = , pre = , tmp;
for (int i = ; i < bucket.size(); ++i) {
if (bucket[i].empty()) continue;
tmp = bucket[i][] - bucket[pre][];
gap = max(gap, tmp);
pre = i;
}
return gap;
}
};
代码二(刚开始我看的一直是这个,代码风格虽然很好,但是不好理解):
这里要用到桶排序,感觉不太感兴趣,就直接看了网上的做法。
(ps:后来才知道,桶排序是基数排序的基础)
C++中vector中的一些常用函数:
取容器中的最大最小值min_element(),max_element()。
当有必要对一个接受pair参数的函数传递两个值时, make_pair()尤其显得方便。
int minAll = *min_element(nums.begin(), nums.end());
int maxAll = *max_element(nums.begin(), nums.end());
vector<pair<int, int> > buckets(bucketCount, make_pair(INT_MIN, INT_MAX));
应用桶排序的思想,把数组元素归到桶中。在一个桶内,元素差小于等于block.max-block.min。在两桶之间,元素差等于block2.min-block1.max。
// 用桶排序
// 算出相邻两个桶之间的最大差值
// 如果是平均分布,则桶的数目和元素的数目相同时,其排序的时间复杂度是0(n)
// 我们假设桶的个数和元素的数目相同,若是平均分布,则每个桶里有一个数,而若某个桶里有两个以上的桶时,这时必有至少一个是空桶,那么最大间隔可能就落在空桶的相邻两个桶存储的数之间,最大间隔不会落在同一个桶的数里,因此我们不需要对每个桶再排一次序,只需要记录同一个桶的最大值和最小值,算出前一个有最大值的桶和后一个有最小值的桶之差,则可能是最大间隔
//步骤:1.算好用的桶的个数,用最大元素和最小元素算出平均间隔,记录在平均间隔上的最大值和最小值,
// 2. 再算出前一个间隔里的最大值和后一个间隔里的最小值之差,取最大的一个,
// 3. 再算出最小值和第二小的差(平均间隔最小值第一个),最大值和第二大(平均间隔最大值最后一个)的差,三个值相比,取最大的,就是最大间隔
class Solution {
public:
int maximumGap(vector<int>& nums) {
if (num.size() < ) return ;
// 1. 算出用的桶数:取平均间隔,再用最大值和最小值之差除以间隔,得到桶数
// 因为假设所有值都是平均分布的时候,如此取桶数可得时间复杂度是0(n)
auto maxVal = *max_element(num.begin(), num.end());
auto minVal = *min_element(num.begin(), num.end());
int agGap = ceil((double)(maxVal - minVal) / (num.size()-)); // 平均间隔
int bucketCount = ceil((double)(maxVal - minVal) / agGap);
// 2. 记录每个桶的最大值和最小值
vector<pair<int, int> > buckets(bucketCount, make_pair(INT_MIN, INT_MAX)); // 初始化桶
for (auto val : num){
if (val == maxVal || val == minVal) continue;
int bucketNum = (val - minVal) / agGap;
if (val > buckets[bucketNum].first)
buckets[bucketNum].first = val; // 存储最大值
if (val < buckets[bucketNum].second) buckets[bucketNum].second = val; // 存储最小值
}
// 3. 算出最大间隔
int maxGap(), lastMax(minVal);
for (auto bucket : buckets){
if (bucket.first == INT_MIN) continue; // 空桶
int curMax(bucket.first), curMin(bucket.second);
maxGap = max(maxGap, curMin - lastMax);
lastMax = curMax;
}
maxGap = max(maxGap, maxVal - lastMax);
return maxGap;
}
};
Maximum Gap——桶排序的更多相关文章
- 线性时间的排序算法--桶排序(以leetcode164. Maximum Gap为例讲解)
前言 在比较排序的算法中,快速排序的性能最佳,时间复杂度是O(N*logN).因此,在使用比较排序时,时间复杂度的下限就是O(N*logN).而桶排序的时间复杂度是O(N+C),因为它的实现并不是基于 ...
- 【leetcode 桶排序】Maximum Gap
1.题目 Given an unsorted array, find the maximum difference between the successive elements in its sor ...
- 由Maximum Gap,对话桶排序,基数排序和统计排序
一些非比较排序 在LeetCode中有个题目叫Maximum Gap.是求一个非排序的正数数列中按顺序排列后的最大间隔.这个题用桶排序和基数排序都能够实现.以下说一下桶排序.基数排序和计数排序这三种非 ...
- Maximum Gap 典型线性排序
https://leetcode.com/problems/maximum-gap/ Given an unsorted array, find the maximum difference betw ...
- ✡ leetcode 164. Maximum Gap 寻找最大相邻数字差 --------- java
Given an unsorted array, find the maximum difference between the successive elements in its sorted f ...
- leetcode[164] Maximum Gap
梅西刚梅开二度,我也记一题. 在一个没排序的数组里,找出排序后的相邻数字的最大差值. 要求用线性时间和空间. 如果用nlgn的话,直接排序然后判断就可以了.so easy class Solution ...
- Bucket Sort - leetcode [桶排序]
桶排序(Bucket sort)或所谓的箱排序,是一个排序算法,工作的原理是将数组分到有限数量的桶里.每个桶再个别排序(有可能再使用别的排序算法或是以递归方式继续使用桶排序进行排序).桶排序是鸽巢排序 ...
- 164. Maximum Gap (Array; sort)
Given an unsorted array, find the maximum difference between the successive elements in its sorted f ...
- Maximum Gap (ARRAY - SORT)
QUESTION Given an unsorted array, find the maximum difference between the successive elements in its ...
随机推荐
- SFM
1.相机模型,内参数和外参数矩阵,相机标定: 2.极线约束和本征矩阵:特征点提取与匹配:提取到的特征点计算本征矩阵(五对以上的点)findEssentialMat(),需啊要点对,焦距参数,cx,cy ...
- Codeforces Round #342 (Div. 2) A
A. Guest From the Past time limit per test 1 second memory limit per test 256 megabytes input standa ...
- ACM1829并查集
A Bug's Life Problem Description Background Professor Hopper is researching the sexual behavior of a ...
- linux下bash脚本语法
1.shell中的变量定义和引用(1)变量定义和初始化.shell是弱类型语言(语言中的变量如果有明确的类型则属于强类型语言:变量没有明确类型就是弱类型语言),和C语言不同.在shell编程中定义变量 ...
- webstorm常用功能快捷方式
1 自动注释和撤销注释:ctrl+/ 在一句代码前面用 ctrl+/ 可以自动注释和撤销注释,js,html都可以,很好的省去了敲注释符的时间 (mac下为command+/,下同) 2 自动补全ht ...
- UVA 11040 Add bricks in the wall
https://vjudge.net/problem/UVA-11040 找规律 #include<cstdio> using namespace std; ][]; int main() ...
- LightOJ 1278 - Sum of Consecutive Integers 分解奇因子 + 思维
http://www.lightoj.com/volume_showproblem.php?problem=1278 题意:问一个数n能表示成几种连续整数相加的形式 如6=1+2+3,1种. 思路:先 ...
- ? 初识Webx 2
初识Webx 1: http://www.cnblogs.com/lddbupt/p/5547189.html Webx Framework负责完成一系列基础性的任务. 比如系统初始化和响应请求. 系 ...
- 「6月雅礼集训 2017 Day10」perm(CodeForces 698F)
[题目大意] 给出一个$n$个数的序列$\{a_n\}$,其中有些地方的数为0,要求你把这个序列填成一个1到$n$的排列,使得: $(a_i, a_j) = 1$,当且仅当$(i, j) = 1$.多 ...
- 51nod 1766 树上的最远点对——线段树
n个点被n-1条边连接成了一颗树,给出a~b和c~d两个区间,表示点的标号请你求出两个区间内各选一点之间的最大距离,即你需要求出max{dis(i,j) |a<=i<=b,c<=j& ...