[leetcode] 164. Maximum Gap 解题报告
2016-05-11 10:50
423 查看
题目链接:https://leetcode.com/problems/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.
思路:一开始就想到基数排序时间和空间复杂度都是线性,不过只有在数字比较集中的时候速度才比较快,也就是其时间复杂度是O(k*n),其中k是最大数字有几位,n是数组长度.所以就想应该不会用这种方法吧,应该还有其他方法,没想到真的是这种算法.坑爹啊!
基数排序不是基于比较的排序算法,是基于RAM的,也就是基于内存的排序.其原理是从低位到高位统计在那一位0-9出现的次数,然后将数组按照那一位的大小排序.
代码如下:
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.
思路:一开始就想到基数排序时间和空间复杂度都是线性,不过只有在数字比较集中的时候速度才比较快,也就是其时间复杂度是O(k*n),其中k是最大数字有几位,n是数组长度.所以就想应该不会用这种方法吧,应该还有其他方法,没想到真的是这种算法.坑爹啊!
基数排序不是基于比较的排序算法,是基于RAM的,也就是基于内存的排序.其原理是从低位到高位统计在那一位0-9出现的次数,然后将数组按照那一位的大小排序.
代码如下:
class Solution { public: int maximumGap(vector<int>& nums) { if(nums.size() < 2) return 0; int len =to_string(*max_element(nums.begin(), nums.end())).size(); int radix=1, maxGap=0, n=nums.size(); for(int i = 0; i< len; i++) { vector<int> count(10, 0), vec(n); for(int val: nums) count[(val/radix)%10]++; for(int j=1; j<10; j++) count[j]+= count[j-1]; for(int j=n-1; j >=0; j--) vec[--count[(nums[j]/radix)%10]] = nums[j]; for(int j =0; j< n; j++) nums[j] = vec[j]; radix *= 10; } for(int i =1; i< n; i++) maxGap=max(maxGap, nums[i]-nums[i-1]); return maxGap; } };
相关文章推荐
- 【框架】ActiveAndroid数据库操作
- iOS8推送消息的快速回复处理
- caffe dataset
- sql点滴39—解决数据库日志文件过大的问题
- HDU 3072 Intelligence System (强连通+(贪心||树形图))
- javascript基础-抢购器与双色球模拟摇奖器
- java 复制图片练习
- ssh配置无密码登录,以及配置完不能登录的解决方法
- js array.find()扩展
- OAuth 2.0的理解
- 浅谈CocoaPods那点事。。。
- 深入了解iOS代理设计模式
- Date类型和Calendar类型区别
- 阿里云Ubuntu服务器配置教程(一)——服务器与MySQL配置
- 将一个字段中以符号分隔的多个数字进行排序显示
- pip 安装其他工具报错处理
- 深入 Linux 的进程优先级
- java 键盘输入数据
- Android性能优化
- c++11时间函数