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

运行结果


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

相关推荐
Tiandaren1 小时前
Selenium 4 教程:自动化 WebDriver 管理与 Cookie 提取 || 用于解决chromedriver版本不匹配问题
selenium·测试工具·算法·自动化
岁忧2 小时前
(LeetCode 面试经典 150 题 ) 11. 盛最多水的容器 (贪心+双指针)
java·c++·算法·leetcode·面试·go
chao_7892 小时前
二分查找篇——搜索旋转排序数组【LeetCode】两次二分查找
开发语言·数据结构·python·算法·leetcode
秋说4 小时前
【PTA数据结构 | C语言版】一元多项式求导
c语言·数据结构·算法
Maybyy4 小时前
力扣61.旋转链表
算法·leetcode·链表
卡卡卡卡罗特6 小时前
每日mysql
数据结构·算法
chao_7897 小时前
二分查找篇——搜索旋转排序数组【LeetCode】一次二分查找
数据结构·python·算法·leetcode·二分查找
蜉蝣之翼❉7 小时前
CRT 不同会导致 fopen 地址不同
c++·mfc
今日热点7 小时前
小程序主体变更全攻略:流程、资料与异常处理方案
经验分享·微信·小程序·企业微信·微信公众平台·微信开放平台
aramae7 小时前
C++ -- STL -- vector
开发语言·c++·笔记·后端·visual studio