堆排序的最大优点就是时间复杂度O(m+n)是线性时间,但是适合区间小,数相对密集的情况
堆排序的算法:
ArrayList<ArrayList<Integer>> bucketSort(int[] nums){
int mn=Integer.MAX_VALUE;
int mx=Integer.MIN_VALUE;
int n=nums.length;
for(int i =0;i<n;i++){
mx=Math.max(mx,nums[i]);
mn=Math.min(mn,nums[i]);
}
//System.out.println(Array.toString(nums))
int bucketNum=(mx-mn)/n+1;
ArrayList<ArrayList<Integer>> bucketArr=new ArrayList<>(bucketNum);
for(int i=0;i<bucketNum;i++){
bucketArr.add(new ArrayList<Integer>());
}
for(int i=0;i<n;i++){
int num=(nums[i]-mn)/n;
bucketArr.get(num).add(nums[i]);
}
for(int i=0;i<bucketNum;i++){
Collections.sort(bucketArr.get(i));
}
System.out.println(bucketArr.toString());
return bucketArr;
}
leetcode的算法:
class Solution {
public:
int maximumGap(vector<int> &numss) {
if (numss.empty()) return 0;
int mx = INT_MIN, mn = INT_MAX, n = numss.size();
for (int d : numss) {
mx = max(mx, d);
mn = min(mn, d);
}
int size = (mx - mn) / n + 1;
int bucket_nums = (mx - mn) / size + 1;
vector<int> bucket_min(bucket_nums, INT_MAX);
vector<int> bucket_max(bucket_nums, INT_MIN);
set<int> s;
for (int d : numss) {
int idx = (d - mn) / size;//属于哪个桶
bucket_min[idx] = min(bucket_min[idx], d);
bucket_max[idx] = max(bucket_max[idx], d);
s.insert(idx);
}
int pre = 0, res = 0;
for (int i = 1; i < n; ++i) { // i<n 可以修改为i<bucket_nums
if (!s.count(i)) continue;
res = max(res, bucket_min[i] - bucket_max[pre]);
pre = i;
}
return res;
}
};