[LeetCode]Maximum Gapd
2015-08-05 00:55
260 查看
一题一句:
下面用桶排序实现,这也是leetcode上给出的参考解法:
Suppose there are N elements and they range from A to B.
Then the maximum gap will be no smaller than ceiling[(B - A) / (N - 1)]
Let the length of a bucket to be len = ceiling[(B - A) / (N - 1)], then we will have at most num = (B - A) / len + 1 of bucket
for any number K in the array, we can easily find out which bucket it belongs by calculating loc = (K - A) / len and therefore maintain the maximum and minimum elements in each bucket.
Since the maximum difference between elements in the same buckets will be at most len - 1, so the final answer will not be taken from two elements in the same buckets.
For each non-empty buckets p, find the next non-empty buckets q, then q.min - p.max could be the potential answer to the question. Return the maximum of all those values.
补充:
Java array is a pain in ass especially after you have tasted python list. But still, need to get used to it.
int bucket_size = Math.max(1,(Max-Min)/(N) + 1);//ceil( (Max-Min)/(N-1) ) = (Max-Min-1)/(N-1) + 1 or int bucket_size = (int)Math.ceil( ((double)(Max-Min))/(N-1) ); int bucket_count = (Max-Min)/bucket_size + 1;
下面用桶排序实现,这也是leetcode上给出的参考解法:
Suppose there are N elements and they range from A to B.
Then the maximum gap will be no smaller than ceiling[(B - A) / (N - 1)]
Let the length of a bucket to be len = ceiling[(B - A) / (N - 1)], then we will have at most num = (B - A) / len + 1 of bucket
for any number K in the array, we can easily find out which bucket it belongs by calculating loc = (K - A) / len and therefore maintain the maximum and minimum elements in each bucket.
Since the maximum difference between elements in the same buckets will be at most len - 1, so the final answer will not be taken from two elements in the same buckets.
For each non-empty buckets p, find the next non-empty buckets q, then q.min - p.max could be the potential answer to the question. Return the maximum of all those values.
补充:
Java array is a pain in ass especially after you have tasted python list. But still, need to get used to it.
相关文章推荐
- iOS应用架构谈 开篇
- 最好最实用的二次开发教程(dedeCMS,ecshop为例)
- bzoj 1623: [Usaco2008 Open]Cow Cars 奶牛飞车
- 数据结构基础温故-6.查找(上):基本查找与树表查找
- 各种版本的ST-LINK仿真器
- inux Gsensor驱动(bma250为例子)
- MinGW-64 安装
- 欢迎使用CSDN-markdown编辑器
- POJ_3660
- Android开源:数据库ORM框架GreenDao学习心得及使用总结
- MTK6572 平台G_SEENSOR兼容
- 2015-08-04
- Android-ViewPagerIndicator框架使用——TitlePageIndicator
- Android4.0 G-Sensor工作流程
- 淘宝宝箱流量软件抽取方法(纯方法) 淘宝js研究
- Xcode小技巧
- Android-Gsensor屏幕旋转
- hdu4918 Query on the subtree
- Linux makefile 教程 非常详细 易懂
- Android.mk文件分析