[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
原创粉丝点击