LeetCode(164)Maximum Gap
2015-12-07 13:08
369 查看
题目
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.
分析
题意为,给定一组无序整数序列,求其有序形式下相邻元素的最大差值;要求,时空复杂度均为线性。
开始还以为题意理解错了,尝试做了一下,利用库排序函数sort排序,然后一次遍历求得最大差值;时间复杂度为O(nlogn),空间复杂度为O(1);没想到AC了;
看来,题目要求如上描述很简单,考察的关键在于能否实现线性的优化也就延伸为排序算法的线性优化;
参考了别人的桶排序实现代码 ^||^… 羞愧的附上~~~
AC代码
class Solution { public: //方法一:STL库函数Sort排序,T(n)=O(nlogn) int maximumGap1(vector<int>& nums) { if (nums.empty() || nums.size() < 2) return 0; int len = nums.size(); sort(nums.begin(), nums.end()); int gap = 0; for (int i = 1; i < len; ++i) { if (nums[i] - nums[i - 1] > gap) gap = nums[i] - nums[i - 1]; }//for return gap; } //方法二:桶排序 int maximumGap(vector<int>& nums) { if (nums.empty() || nums.size() < 2) return 0; int n = nums.size(); int minAll = *min_element(nums.begin(), nums.end()); int maxAll = *max_element(nums.begin(), nums.end()); // type conversion!!! double gap = ((double)(maxAll - minAll)) / (n - 1); // compute min and max element for each bucket vector<int> minV(n - 1, INT_MAX); vector<int> maxV(n - 1, INT_MIN); for (int i = 0; i < n; i++) { if (nums[i] != maxAll) {// the bktId of maxAll will fall out of bucket range int bktId = (int)((nums[i] - minAll) / gap); minV[bktId] = min(minV[bktId], nums[i]); maxV[bktId] = max(maxV[bktId], nums[i]); } } int ret = 0; int curMax = maxV[0]; for (int i = 1; i < n - 1; i++) { if (minV[i] != INT_MAX) { ret = max(ret, minV[i] - curMax); curMax = maxV[i]; } } ret = max(ret, maxAll - curMax); return ret; } };
GitHub测试程序源码
相关文章推荐
- Nginx 内置全局变量
- LeetCode(164)Maximum Gap
- 类别扩展属性
- iOS中UITextField、UITextView的字数限制
- 《Swift 的界面之间的传值,详细介绍3种传值方式》 正向传值、协议传值、闭包
- Android最新动画框架完全解析(一)—— Animator(Property Animation)
- 黑马程序员——OC基础---Foundation<NSArray补充,NSMultableArray,NSDictionary>
- Tree -- Traverse & DFS & BFS
- tp框架中空操作和空控制器处理方法
- ant 安装
- Linux系统搭建yum仓库
- 学习php设计模式 php实现原型模式(prototype)
- java int与byte【】之间的转换
- PHP 如何查看AJAX返回的对象和数组的内容
- MVC HtmlHelper用法大全
- ie11的DOM管理器报错
- python核心编程-GUI例子
- 【数据结果与算法】插入排序算法
- iOS中 蓝牙2.0详解/ios蓝牙设备详解 韩俊强的博客
- iOS中 蓝牙2.0详解/ios蓝牙设备详解 韩俊强的博客