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.

给定一个未排序的数组,然后找出排序之后的数组中,相邻数字的最大差。

1、桶排序

public class Solution {
public int maximumGap(int[] nums) {
int len = nums.length;
if (len < 2){
return 0;
}
int max = nums[0];
int min = nums[0];
for (int num : nums){
if (max < num){
max = num;
} else if ( min > num){
min = num;
}
}
int gap = (max-min)/(len-1);
if( gap == 0){
gap = 1;
}
int size = (max - min) / gap + 1;
int[] gapMax = new int[size];
int[] gapMin = new int[size];
for (int num : nums){
int pos = (num - min)/gap;
if (gapMax[pos] < num){
gapMax[pos] = num;
}
if (gapMin[pos] == 0 || gapMin[pos] > num){
gapMin[pos] = num;
}
}
int start = min;
int end = gapMax[0];
int result = end - start;
for (int i = 0; i < size - 1; i++){
start = gapMax[i] == 0 ? start : gapMax[i];
end = gapMin[i+1];
if (result < (end - start)){
result = end - start;
}
}
if (gapMax[size - 1] == 0 && end - start > result){
result = end - start;
} else if (gapMax[size - 1] != 0 && end - gapMax[size - 1] > result){
result = end - gapMax[size - 1];
}
return result;
}
}

最新文章

  1. Codeforces Round #161 (Div. 2) D. Cycle in Graph(无向图中找指定长度的简单环)
  2. :first-child 类似的 :first 匹配第一个元素,但是:first-child选择器可以匹配多个:即为每个父级元素匹配第一个子元素。这相当于:nth-child(1)
  3. IIS7.5 发布程序后cookie丢失问题
  4. C#外挂QQ找茬辅助源码,早期开发
  5. PHP面向对象(PHP对象在内存中的分配)
  6. 发现一个可以在线运行JS代码的网站
  7. 安卓kernel自主唤醒系统方法—设置alarm
  8. c# WPF 项目优化
  9. 我的第一个Android开源库——CirclePointMove中文文档(可随Viewpager移动的指示器)
  10. script标签中type为&quot;text/x-template&quot;或&quot;text/html&quot;
  11. {Python之进程} 背景知识 什么是进程 进程调度 并发与并行 同步\异步\阻塞\非阻塞 进程的创建与结束 multiprocess模块 进程池和mutiprocess.Poll
  12. eclipse几种常见问题的解决
  13. tornado学习笔记
  14. 浏览器存储:cookie
  15. finger-guessing game:1场景搭建
  16. iBatis与Hibernate有什么不同?
  17. Python3.5 学习十
  18. Python 入门学习(壹)上机时间提醒
  19. Collections.singletonList方法的使用
  20. python 装饰器的详细理解【多次实验】

热门文章

  1. Install Google Pinyin on Ubuntu 14.04
  2. Json2JsonArray JsonArray2StringArray
  3. CSS3中的2D转换
  4. Hibernate 中出现 XXXX is not mapped 问题
  5. JQuery_过滤选择器
  6. GPRS模块上电后复位会导致开机函数不正常的问题原因及解决方法
  7. NGUI Camera&#39;s raycast hit through the UI Layer issue
  8. java_easyui体系之目录 [转]
  9. UE3植被工具-支持刷Actor)
  10. Xcode6.1标准Framework静态库制作方法。工程转Framework,静态库加xib和图片。完美解决方案。