✡ leetcode 164. Maximum Gap 寻找最大相邻数字差 --------- java
2024-10-20 21:04:48
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;
}
}
最新文章
- Codeforces Round #161 (Div. 2) D. Cycle in Graph(无向图中找指定长度的简单环)
- :first-child 类似的 :first 匹配第一个元素,但是:first-child选择器可以匹配多个:即为每个父级元素匹配第一个子元素。这相当于:nth-child(1)
- IIS7.5 发布程序后cookie丢失问题
- C#外挂QQ找茬辅助源码,早期开发
- PHP面向对象(PHP对象在内存中的分配)
- 发现一个可以在线运行JS代码的网站
- 安卓kernel自主唤醒系统方法—设置alarm
- c# WPF 项目优化
- 我的第一个Android开源库——CirclePointMove中文文档(可随Viewpager移动的指示器)
- script标签中type为";text/x-template";或";text/html";
- {Python之进程} 背景知识 什么是进程 进程调度 并发与并行 同步\异步\阻塞\非阻塞 进程的创建与结束 multiprocess模块 进程池和mutiprocess.Poll
- eclipse几种常见问题的解决
- tornado学习笔记
- 浏览器存储:cookie
- finger-guessing game:1场景搭建
- iBatis与Hibernate有什么不同?
- Python3.5 学习十
- Python 入门学习(壹)上机时间提醒
- Collections.singletonList方法的使用
- python 装饰器的详细理解【多次实验】
热门文章
- Install Google Pinyin on Ubuntu 14.04
- Json2JsonArray JsonArray2StringArray
- CSS3中的2D转换
- Hibernate 中出现 XXXX is not mapped 问题
- JQuery_过滤选择器
- GPRS模块上电后复位会导致开机函数不正常的问题原因及解决方法
- NGUI Camera&#39;s raycast hit through the UI Layer issue
- java_easyui体系之目录 [转]
- UE3植被工具-支持刷Actor)
- Xcode6.1标准Framework静态库制作方法。工程转Framework,静态库加xib和图片。完美解决方案。