博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LintCode] Maximum Gap 求最大间距
阅读量:7061 次
发布时间:2019-06-28

本文共 1630 字,大约阅读时间需要 5 分钟。

Given an unsorted array, find the maximum difference between the successive elements in its sorted form.

Return 0 if the array contains less than 2 elements.

 Notice

You may assume all elements in the array are non-negative integers and fit in the 32-bit signed integer range.

Example

Given [1, 9, 2, 5], the sorted form of it is[1, 2, 5, 9], the maximum gap is between 5and 9 = 4.

Sort is easy but will cost O(nlogn) time. Try to solve it in linear time and space.

LeetCode上的原题,请参见我之前的博客。

class Solution {public:    /**     * @param nums: a vector of integers     * @return: the maximum difference     */    int maximumGap(vector
nums) { if (nums.empty()) return 0; int mx = INT_MIN, mn = INT_MAX, n = nums.size(); for (int d : nums) { mx = max(mx, d); mn = min(mn, d); } int size = (mx - mn) / n + 1; int bucket_num = (mx - mn) / size + 1; vector
bucket_min(bucket_num, INT_MAX); vector
bucket_max(bucket_num, INT_MIN); set
s; for (int d : nums) { int idx = (d - mn) / size; bucket_min[idx] = min(bucket_min[idx], d); bucket_max[idx] = max(bucket_max[idx], d); s.insert(idx); } int pre = 0, res = 0; for (int i = 1; i < n; ++i) { if (!s.count(i)) continue; res = max(res, bucket_min[i] - bucket_max[pre]); pre = i; } return res; }};

本文转自博客园Grandyang的博客,原文链接:,如需转载请自行联系原博主。

你可能感兴趣的文章
Linux网络相关、firewalld和netfilter
查看>>
linux基础(day30)
查看>>
四周第五次课(11月10日) 6.5 zip压缩工具 6.6 tar打包 6.7 打包并压缩
查看>>
财务管理后台(前台页面)
查看>>
解决hash冲突的4种方法
查看>>
Kafka简介及安装配置
查看>>
Redis——HyperLogLog
查看>>
市场分享竞品分析
查看>>
科技兴国园区兴城——2019国际高科技产业园区博览会在深盛装开幕
查看>>
计网——TCP连接管理(三次握手、四次握手)
查看>>
CentOS 7.4进入单用户模式
查看>>
中国联通与阿里云达成合作,推动5G+新媒体产业发展
查看>>
汇总rsync使用中错误信息
查看>>
学习Linux 第三课
查看>>
Jenkins. 安装过程中出现一个错误: No such plugin: cloudbees-folder
查看>>
股市一片红,3100守住
查看>>
XStream转换时忽略未知字段
查看>>
图像添加到ABBYY 文档有什么方法
查看>>
Hibernate 4 之buildSessionFactory方法废弃问题
查看>>
搭建本地Ubuntu 镜像服务器
查看>>