[leetcode] 164. Maximum Gap 解题报告
来源:互联网 发布:火影忍者网络连接错误 编辑:程序博客网 时间:2024/05/29 07:10
题目链接: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出现的次数,然后将数组按照那一位的大小排序.
代码如下:
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; }};
0 0
- [leetcode] 164. Maximum Gap 解题报告
- [Leetcode] 164. Maximum Gap 解题报告
- [LeetCode]164.Maximum Gap
- [LeetCode]164. Maximum Gap
- LeetCode 164. Maximum Gap
- LeetCode 164. Maximum Gap
- leetcode.164. Maximum Gap
- [LeetCode] 164. Maximum Gap
- [leetcode] 164. Maximum Gap
- LeetCode 164. Maximum Gap
- LeetCode 164. Maximum Gap
- 164. Maximum Gap [leetcode]
- leetcode 164. Maximum Gap
- LeetCode 164. Maximum Gap
- LCP164 LeetCode 164. Maximum Gap
- [LeetCode]problem 164. Maximum Gap
- [LeetCode] Maximum Subarray 解题报告
- 【LeetCode】Maximum Subarray 解题报告
- linux 32位 pae
- java 字节输入输出流
- Activity动态添加Fragment
- html5 record 修改采样率导致声音无法播放解决方案
- Dynamics CRM2016 Update or Create parentcustomerid in Contact using web api
- [leetcode] 164. Maximum Gap 解题报告
- leetcode笔记—Reorder List
- ElasticSearch之初识
- 【MySql性能优化一】性能测试环境配置和慢查询日志的使用
- HDU 3072 Intelligence System (强连通+(贪心||树形图))
- Activity 启动模式
- MinGW安装和使用
- 【Lua】windows下安装和使用LuaJIT步骤
- Java Web中的EL(表达式语言)详解