Leetcode—164. 最大间距【中等】(struct)

2024每日刷题(157)

Leetcode---164. 最大间距

直接法实现代码

cpp 复制代码
class Solution {
public:
    int maximumGap(vector<int>& nums) {
        int n = nums.size();
        if(n == 1) {
            return 0;
        }
        ranges::sort(nums);
        int diff = -1;
        int pre = nums[0];
        for(int i = 1; i < n; i++) {
            diff = max(diff, nums[i] - pre);
            pre = nums[i];
        }
        return diff;
    }
};

运行结果

桶排序算法思想

桶排序法实现代码

cpp 复制代码
struct Bucket {
    int mn;
    int mx;
};

class Solution {
public:
    int maximumGap(vector<int>& nums) {
        int mn = ranges::min(nums);
        int mx = ranges::max(nums);

        int n = nums.size();

        if(n < 2) {
            return 0;
        }

        if(mn == mx) {
            return 0;
        }
        int bucketVol = ceil((mx - mn) / (double)(n - 1)); 
        int bucketSize = (mx - mn) / bucketVol + 1;
        vector<Bucket> bt(bucketSize, {INT_MAX, INT_MIN});

        for(int i = 0; i < n; i++) {
            int cursor = (nums[i] - mn) / bucketVol;
            bt[cursor].mn = min(bt[cursor].mn, nums[i]);
            bt[cursor].mx = max(bt[cursor].mx, nums[i]);
        }

        int preMax = bt[0].mx;
        int ans = 0;
        for(int i = 1; i < bucketSize; i++) {
            if(bt[i].mn == INT_MAX) {
                continue;
            }

            ans = max(bt[i].mn - preMax, ans);
            preMax = bt[i].mx;
        }
        return ans;
    }
};

运行结果


之后我会持续更新,如果喜欢我的文章,请记得一键三连哦,点赞关注收藏,你的每一个赞每一份关注每一次收藏都将是我前进路上的无限动力 !!!↖(▔▽▔)↗感谢支持!

相关推荐
姜不吃葱9 分钟前
【力扣热题100】双指针—— 接雨水
数据结构·算法·leetcode·力扣热题100
PineappleCoder14 分钟前
大小写 + 标点全搞定!JS 如何精准统计单词频率?
前端·javascript·算法
雨落倾城夏未凉18 分钟前
5.通过拷贝构造函数复制一个对象,假如对象的成员中有个指针类型的变量,如何避免拷贝出来的副本中的该成员之下行同一块内存(等价于默认拷贝构造函数有没有缺点)
c++·后端
雨落倾城夏未凉20 分钟前
4.深拷贝VS浅拷贝
c++·后端
zzx_blog23 分钟前
简单易懂的leetcode 100题-第三篇 移动0,颜色分类,数组中的第K个最大元素
leetcode·面试
tanyongxi661 小时前
C++ 特殊类设计与单例模式解析
java·开发语言·数据结构·c++·算法·单例模式
qq_513970441 小时前
力扣 hot100 Day76
算法·leetcode·职场和发展
fqbqrr1 小时前
2508C++,支持rdma通信的高性能rpc库
c++·rpc
Moshow郑锴2 小时前
机器学习相关算法:回溯算法 贪心算法 回归算法(线性回归) 算法超参数 多项式时间 朴素贝叶斯分类算法
算法·机器学习·回归
liulilittle2 小时前
BFS寻路算法解析与实现
开发语言·c++·算法·宽度优先·寻路算法·寻路