[LeetCode][JavaScript]Maximum Gap
2015-06-26 23:37
701 查看
Maximum Gap
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/
这道题正确的姿势是先随便写一把快排交过了,然后去看Solution。 233
原版Solution解释得很清楚了,抽屉原理+箱排序。
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.
Analysis written by @porker2008.
/** * @param {number[]} nums * @return {number} */ var maximumGap = function(nums) { if(nums.length < 2){ return 0; } var boxMap = {}; var max = Math.max.apply(null, nums); var min = Math.min.apply(null, nums); var vol = parseInt((max - min) / (nums.length - 1)); if(vol === 0){ vol = 1; } var i = 0, box = null, curr = null; for(i = 0; i < nums.length; i++){ curr = nums[i]; box = parseInt((curr - min) / vol); if(!boxMap[box]){ boxMap[box] = {max : curr, min : curr}; }else{ if(curr > boxMap[box].max){ boxMap[box].max = curr; }else if(curr < boxMap[box].min){ boxMap[box].min = curr; } } } var maxGap = -Infinity; var previousMax = null; for(i in boxMap){ if(previousMax && (boxMap[i].max - previousMax)> maxGap){ maxGap = boxMap[i].min - previousMax; } previousMax = boxMap[i].max; } return maxGap; };
相关文章推荐
- Javascript进度条
- js的类型转换
- js跨越小结
- 那些逐步掌握的JavaScript('use strict')
- setInterval 和 setTimeout 的区别 JS学习笔记2015-6-26(第67天)
- 20150623 javascript实现的简单刷贴
- 《webgl入门指南》学习笔记二之three.js创建mesh
- JS ajax 后台交互
- JS Library Set
- HTML5 Localstorage JS
- js,jq获取浏览器宽度,高度等值(多浏览器)
- echop JS Library
- js实现表格排序(正序和反序)
- javaScript实现日历控件
- Javascript模块化工具require.js教程
- js 变量 赋予默认值
- Json的序列化与反序列化以及乱入的k_BackingField
- 在arcgis javascript 中map地图的div 总是显示高度400的问题
- ExtJs布局中,控件如何水平居中?
- ExtJs布局中,控件如何水平居中?