leetcode Maximum Gap
来源:互联网 发布:最新在线报名系统源码 编辑:程序博客网 时间:2024/06/08 19:56
题目
Given an unsorted array, find the maximum difference between the successive elements in its sorted form.
Try to solve it in linear time/space.
Return 0 if the array contains less than 2 elements.
You may assume all elements in the array are non-negative integers and fit in the 32-bit signed integer range.
题目来源:https://leetcode.com/problems/maximum-gap/
分析
一个没有排序的数组,返回排好序后的相邻之间元素的最大间隔。
苦思冥想想不出来,参考了一下网上的的做法(参考链接),自己慢慢消化吧。使用若干个桶存放所有元素,使得最大的gap位于两个桶之间(前面桶的最小值和随后桶的最大值之差)。这样的话,桶的数目该是多少位宜呢?平均分割元素区间(max_elm - min_elm),每个区间的大小是一个avg_gap。这样的话,如果所有元素平均分布,则每个桶里一个元素,退化为排序。如果不平均分布,则必然有的桶为空,有的桶里面的元素多于1个。最大的gap也就不可能出现在一个桶里面,求不同桶之间的gap就行了。
代码
class Solution {public: int maximumGap(vector<int>& nums) { int len = nums.size(); if(len < 2) return 0; //find max element int max_num = *max_element(nums.begin(), nums.end()); //find min element int min_num = *min_element(nums.begin(), nums.end()); //average gap, ceil(0.3) = 1 int avg_gap = ceil((double)(max_num - min_num)/(len - 1)); int bucket_num = ceil((double)(max_num - min_num) / avg_gap); //buckets.first is max element in this bucket, initialized by the min integer(0x80000000) //buckets.second is min element in this bucket, initialized by the max integer(0x7fffffff) vector<pair<int, int> >buckets(bucket_num, make_pair(0x80000000, 0x7fffffff)); for(auto val : nums){ if(val == max_num || val == min_num) continue; int i = (val - min_num) / avg_gap;//find the correct bucket if(val > buckets[i].first) buckets[i].first = val; if(val < buckets[i].second) buckets[i].second = val; } int max_gap = 0; int last_max = min_num; for(auto bucket : buckets){ if(bucket.first == 0x80000000)//empty bucket continue; int cur_max = bucket.first; int cur_min = bucket.second; max_gap = max(max_gap, cur_min - last_max); last_max = cur_max; } max_gap = max(max_gap, max_num - last_max); return max_gap; }};
0 0
- leetcode-Maximum Gap
- [LeetCode] Maximum Gap
- LeetCode Maximum Gap
- [leetCode] Maximum Gap
- leetcode 155: Maximum Gap
- LeetCode(164) Maximum Gap
- [LeetCode] Maximum Gap
- [leetcode 164] Maximum Gap
- [leetcode]Maximum Gap
- LeetCode - Maximum Gap 题解
- Maximum Gap|leetcode题解
- LeetCode[Sort]: Maximum Gap
- [LeetCode] Maximum Gap
- leetcode maximum gap
- [LeetCode]Maximum Gap
- LeetCode OJ Maximum Gap
- LeetCode Maximum Gap
- 【leetcode】 Maximum Gap
- 浓浓新华情 温暖大家庭
- 软考总计之白盒测试中的覆盖
- cc1plus.exe: out of memory allocating 3355443200 bytes
- [Java]交换排序
- 【AOP】借助容器将服务与代理类分离
- leetcode Maximum Gap
- 二叉树的遍历(前序+中序+后序)
- 使用Ibatis操作MySQL数据库
- Andriod SDK出现Failed to parse the output of 'adb version'问题
- leetcode 11 -- Container With Most Water
- USACO--3.3A Game+dp
- 我的Cocos2d-x学习笔记(十)定时调度器(scheduleUpdate、scheduleOnce、schedule)
- 《C Primer Plus(第5版)中文版》第7章编程练习第8题
- html+css注意事项