1、题目

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.

2、分析

题意:给定一个未排序的数组。返回其排序后的数组中 相邻元素之差 最大的值。

比方给定:[5,9,8,3,15]

排序后为:[3,5,8,9,15]。相邻元素之差最大的是15-9=6,返回6。

复杂度要求:时间空间均为O(n)。

这道题最直接的解法是,先排序,得到有序数组。然后再对相邻元素作差。找出差最大的,比方以下简短的代码:

class Solution {
public:
int maximumGap(vector<int> &num) {
if(num.size()<2) return 0;
sort(num.begin(),num.end()); //O(nlogn)
int gap=-1;
for(int i=1;i<num.size();i++){
gap=max(gap,num[i]-num[i-1]);
}
return gap;
}
};

在Leetcode上上面的代码能够AC,但其实并没有满足时间复杂度要求。由于STL函数sort()的复杂度是O(nlogn),【sort C++ reference】

那么。线性的排序算法有哪些?计数排序、基数排序、桶排序。

以下用桶排序实现。这也是leetcode上给出的參考解法。我直接copy过来:

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.

依据上面的思路。得到代码例如以下:

class Solution {
public:
int maximumGap(vector<int> &num) {
if (num.size() < 2) return 0;
//遍历一遍。找出最大最小值
int maxNum = num[0];
int minNum = num[0];
for (int i : num) {
maxNum=max(maxNum,i);
minNum=min(minNum,i);
}
// 每一个桶的长度len,向上取整所以加+
int len = (maxNum - minNum) / num.size() + 1; //桶的个数:(maxNum - minNum) / len + 1,每一个桶里面存储属于该桶的最大值和最小值就可以,注意这里的最大最小值是局部的
vector<vector<int>> buckets((maxNum - minNum) / len + 1);
for (int x : num) {
int i = (x - minNum) / len;
if (buckets[i].empty()) {
buckets[i].reserve(2);
buckets[i].push_back(x);
buckets[i].push_back(x);
} else {
if (x < buckets[i][0]) buckets[i][0] = x;
if (x > buckets[i][1]) buckets[i][1] = x;
}
}
//gap的计算,For each non-empty buckets p, find the next non-empty buckets q, return min( q.min - p.max )
int gap = 0;
int prev = 0;
for (int i = 1; i < buckets.size(); i++) {
if (buckets[i].empty()) continue;
gap = max(gap, buckets[i][0] - buckets[prev][1]);
prev = i;
}
return gap;
}
};

【其它解法以后再更新】


【leetcode 桶排序】Maximum Gap的更多相关文章

  1. LeetCode 笔记28 Maximum Gap

    Given an unsorted array, find the maximum difference between the successive elements in its sorted f ...

  2. Bucket Sort - leetcode [桶排序]

    桶排序(Bucket sort)或所谓的箱排序,是一个排序算法,工作的原理是将数组分到有限数量的桶里.每个桶再个别排序(有可能再使用别的排序算法或是以递归方式继续使用桶排序进行排序).桶排序是鸽巢排序 ...

  3. 【LeetCode】164. Maximum Gap (2 solutions)

    Maximum Gap Given an unsorted array, find the maximum difference between the successive elements in ...

  4. 【刷题-LeetCode】164 Maximum Gap

    Maximum Gap Given an unsorted array, find the maximum difference between the successive elements in ...

  5. [LeetCode] 桶排序的特殊解,例 Sort Color

    Sort Colors Given an array with n objects colored red, white or blue, sort them so that objects of t ...

  6. 【Leetcode】164. Maximum Gap 【基数排序】

    Given an unsorted array, find the maximum difference between the successive elements in its sorted f ...

  7. 由Maximum Gap,对话桶排序,基数排序和统计排序

    一些非比较排序 在LeetCode中有个题目叫Maximum Gap.是求一个非排序的正数数列中按顺序排列后的最大间隔.这个题用桶排序和基数排序都能够实现.以下说一下桶排序.基数排序和计数排序这三种非 ...

  8. 线性时间的排序算法--桶排序(以leetcode164. Maximum Gap为例讲解)

    前言 在比较排序的算法中,快速排序的性能最佳,时间复杂度是O(N*logN).因此,在使用比较排序时,时间复杂度的下限就是O(N*logN).而桶排序的时间复杂度是O(N+C),因为它的实现并不是基于 ...

  9. Maximum Gap——桶排序

    Given an unsorted array, find the maximum difference between the successive elements in its sorted f ...

随机推荐

  1. Shell 学习笔记之函数

    hello_fun(){ echo "hello world" echo "$1" # 第一个参数,其中第0个参数为文件本身 } hello_fun 1 在函数 ...

  2. JDK环境变量的配置说明

    一.Linux下的JDK安装及配置: 1. 使用命令uname –a查看系统的版本确定系统的位数,然后去JDK官网下载相应位数的安装程序,进行安装. 2.  使用rz命令将下载的JDK上传至Linux ...

  3. IO流-批量修改文件名称案例

    /* *   源文件名:   桌面-我们今天学习IO流了哈哈哈哈-001.jpg *   修改后文件名:  桌面-000x.jpg */public class File_listFiles_upda ...

  4. 强烈推荐:Android史上最强大的自定义任务软件Tasker

    强烈推荐:Android史上最强大的自定义任务软件Taskerhttp://bbs.mumayi.com/thread-28387-1-1.html(出处: 木蚂蚁手机乐园) Android上的Tas ...

  5. [asp.net web api] HttpStatusCode的使用

    摘要 在开放api的时,我们需要返回不同的状态给调用方,以告诉它们当前请求的结果,是成功了还是失败了.当然这种给调用方的反馈有很多种做法,这里就说是web api内置的对Http状态码.http状态码 ...

  6. win7 启动管理器修改默认启动项

    最近给我的超级本做了系统备份,以防万一,但是备份完成后,系统启动的时候总会首先进入Windows启动管理器,且默认启动项是Ghost,还需要选择一下才能进入Win7系统,如何解决这个问题呢? 方案一: ...

  7. 【微信小程序】在微信开发工具上七牛云的图片可以看到,但是在真机上看不到的原因解决

    在开发微信小程序过程中,在微信开发者工具上,七牛云的图片都可以展示出来,但是在真机上,七牛云的图片却展示不出来,也没有报404找不到或者不能加载图片的问题, 必须保证: 1.图片是用image加载的: ...

  8. 聊聊高并发(十四)理解Java中的管程,条件队列,Condition以及实现一个堵塞队列

    这篇里面有一些主要的概念,理解概念是件有意义的事情,仅仅有理解概念才干在面对详细问题的时候找到正确的解决思路.先看一下管程的概念 第一次在书上看到管程这个中文名称认为非常迷糊,管程究竟是个什么东东,于 ...

  9. .NET:通过 CAS 来理解数据库乐观并发控制,顺便给出无锁的 RingBuffer。

    背景 大多数企业开发人员都理解数据库乐观并发控制,不过很少有人听说过 CAS(我去年才听说这个概念),CAS 是多线程乐观并发控制策略的一种,一些无锁的支持并发的数据结构都会使用到 CAS,本文对比 ...

  10. Selenium2+python自动化51-unittest简介

    前言 熟悉java的应该都清楚常见的单元测试框架Junit和TestNG,这个招聘的需求上也是经常见到的.python里面也有单元测试框架-unittest,相当于是一个python版的junit. ...