[C++]LeetCode 164. 最大间距

编程入门 行业动态 更新时间:2024-10-22 20:25:30

[C++]LeetCode 164. 最大<a href=https://www.elefans.com/category/jswz/34/1761496.html style=间距"/>

[C++]LeetCode 164. 最大间距

题目

给定一个无序的数组,找出数组在排序之后,相邻元素之间最大的差值。
如果数组元素个数小于 2,则返回 0。
示例 1:
输入: [3,6,9,1]
输出: 3
解释: 排序后的数组是[1,3,6,9], 其中相邻元素 (3,6)(6,9)之间都存在最大差值 3
示例 2:
输入: [10]
输出: 0
解释: 数组元素个数小于 2,因此返回0
说明:

  • 你可以假设数组中所有元素都是非负整数,且数值在 32 位有符号整数范围内。
  • 请尝试在线性时间复杂度和空间复杂度的条件下解决此问题。

解题思路

考虑用分桶法,一个数组最小值为low,最大值为high,如果数组在lowhigh之间均匀分布,得到的最大差值是最小的,比如数组[1,3,5,7,9],差值为2,而数组[1,3,4,5,9],最大差值是4,虽然两个数组最小值和最大值以及元素数目均相同。
所以考虑分桶,桶的容量为(high-low)/n,其中n为元素的数组,则 最大差值一定大于桶的容量 。而桶的个数为(high-low)/桶的容量+1,然后找出每个桶的最大值和最小值,那么最大差值一定是桶之间的最大间隔。

代码

class Solution {
public:int maximumGap(vector<int>& nums) {int n=nums.size();if(n<=1) return 0;int low=nums[0],high=nums[0];//low high表示数组中最小值和最大值for(auto m:nums){low=min(low,m);high=max(high,m);}int count=(high-low)/n;//两种case  [2 2 2 2 2] 和[1 1 1 3 3 3 3 3 3]if(high==low) return 0;else if(count==0) count=1;vector<vector<int>> res((high-low)/count+1,vector<int>(2,-1));for(auto m:nums){int t=(m-low)/count;res[t][0]=res[t][0]==-1?m:min(res[t][0],m);res[t][1]=res[t][1]==-1?m:max(res[t][1],m);}int gap=0,left=-1;for(int i=0;i<res.size();i++){if(res[i][0]==-1) continue;else if(left!=-1)gap=max(gap,res[i][0]-left);left=res[i][1];}return gap;}
};

方法二

代码:

class Solution {
public:int maximumGap(vector<int>& nums) {int n=nums.size(),res=0;set<int> s;for(auto &m:nums) s.insert(m);for(auto &m:nums){auto it=s.find(m);if(it!=s.begin()){it--;res=max(res,m-(*it));}}return res;}
};

更多推荐

[C++]LeetCode 164. 最大间距

本文发布于:2024-02-10 19:03:06,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1676825.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:间距   LeetCode

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!