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;
    }
};

运行结果


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

相关推荐
2503_94697186几秒前
【BruteForce/Pruning】2026年度物理层暴力破解与神经网络剪枝基准索引 (Benchmark Index)
人工智能·神经网络·算法·数据集·剪枝·网络架构·系统运维
ChoSeitaku1 分钟前
15.C++入门:list|构造|使用|迭代器失效
开发语言·c++·list
R&ain5 分钟前
C++中的深浅拷贝
开发语言·c++
R&ain5 分钟前
C++的内联函数
c++·算法
羑悻的小杀马特6 分钟前
gflags+spdlog实战:C++命令行参数与高性能日志的极致搭配行动指南
c++·spdlog·gflags
zhmc6 分钟前
常用周期函数的傅里叶级数
人工智能·算法
宝宝单机sop7 分钟前
家庭教育资源合集
经验分享
漫随流水1 小时前
leetcode算法(111.二叉树的最小深度)
数据结构·算法·leetcode·二叉树
fpcc1 小时前
跟我学C++中级篇——Linux中文件和链接及重定向
linux·c++
Fcy6482 小时前
C++ set&&map的模拟实现
开发语言·c++·stl