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

运行结果


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

相关推荐
小庞在加油43 分钟前
《dlib库中的聚类》算法详解:从原理到实践
c++·算法·机器学习·数据挖掘·聚类
ComputerInBook1 小时前
C++ 标准模板库算法之 transform 用法
开发语言·c++·算法·transform算法
2301_803554524 小时前
c++中类的前置声明
java·开发语言·c++
hn小菜鸡7 小时前
LeetCode 377.组合总和IV
数据结构·算法·leetcode
Deepoch7 小时前
Deepoc 大模型:无人机行业的智能变革引擎
人工智能·科技·算法·ai·动态规划·无人机
heimeiyingwang9 天前
【深度学习加速探秘】Winograd 卷积算法:让计算效率 “飞” 起来
人工智能·深度学习·算法
LyaJpunov9 天前
深入理解 C++ volatile 与 atomic:五大用法解析 + 六大高频考点
c++·面试·volatile·atomic
小灰灰搞电子9 天前
Qt PyQt与PySide技术-C++库的Python绑定
c++·qt·pyqt
时空自由民.9 天前
C++ 不同线程之间传值
开发语言·c++·算法
ai小鬼头9 天前
AIStarter开发者熊哥分享|低成本部署AI项目的实战经验
后端·算法·架构