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

运行结果


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

相关推荐
violet-lz1 分钟前
C++ 内存分区详解
开发语言·jvm·c++
小张成长计划..12 分钟前
【C++】20:set和map的理解和使用
c++
weixin_5372170635 分钟前
亲子教育资源合集
经验分享
曼巴UE537 分钟前
UE C++ 字符串编码转码
c++·ue5
智驱力人工智能40 分钟前
仓库园区无人机烟雾识别:构建立体化、智能化的早期火灾预警体系 无人机烟雾检测 无人机动态烟雾分析AI系统 无人机辅助火灾救援系统
人工智能·opencv·算法·目标检测·架构·无人机·边缘计算
Christo31 小时前
2022-《Deep Clustering: A Comprehensive Survey》
人工智能·算法·机器学习·数据挖掘
青山是哪个青山1 小时前
第三节:CMake 工程实践场景笔记
c++·cmake
Yzzz-F1 小时前
牛客周赛round123 G小红出千[补题][滑动窗口]
算法
TeleostNaCl2 小时前
OpenWrt | 使用 nftables 规则禁用小明投影仪内置 DoT 服务的流量
经验分享·智能路由器·电视盒子·智能电视·tv·智能tv
肆悟先生2 小时前
3.16 含有可变参数的函数
c++·算法