码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode | Maximum Gap

时间:2015-07-20 16:34:03      阅读:158      评论:0      收藏:0      [点我收藏+]

标签:linear-sor   sorted   

Maximum Gap: 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.

e.g. [1, 3, 6, 9] return 3.


解析:
题目要求,找出排序后的相邻元素间最大差值。那么首先不得不做的就是排序,而常规的比较排序算法,不能突破O(nlgn),要满足题目要求的线性复杂度,只能选用线性排序算法
线性排序算法:计数排序,基数排序,桶排序点击查看线性排序算法
由于待排序数的范围可能较大,如果使用计数排序或桶排序可能需要较大的空间。
本题采用基数排序 : 时间复杂度O(kn) 空间复杂度 O(n)

class Solution {
public:
    int maximumGap(vector<int>& nums) {
        int size = nums.size();
        if (size < 2)
            return 0;
        radixSort(nums);
        int *gap = new int[size - 1];
        for (int i = 0; i < size - 1; i++)
            gap[i] = nums[i + 1] - nums[i];
        int maxGap = gap[0];
        for (int i = 1; i < size - 1; i++) {
            if (gap[i] > maxGap)
                maxGap = gap[i];
        }
        delete gap;
        return maxGap;
    }
private:
    void radixSort(vector<int>& nums) {
        int size = nums.size();
        int d = getMaxBits(nums); // 得到最大数的位数
        int *count = new int[10]; // 10个桶 0~9
        int* tmp = new int[size];
        int radix = 1;
        for (int i = 0; i < d; i++) {
            for (int j = 0; j < 10; j++)
                count[j] = 0;
            for (int j = 0; j < size; j++) {
                int k = nums[j] / radix % 10;
                count[k]++;
            }
            for (int j = 1; j < 10; j++)
                count[j] += count[j - 1];
            for (int j = size - 1; j >= 0; j--) {
                int k = nums[j] / radix % 10;
                tmp[count[k] - 1] = nums[j];
                count[k]--;
            }
            for (int j = 0; j < size; j++)
                nums[j] = tmp[j];
            radix *= 10;
        }
        delete count;
        delete tmp;

    }
    // 计算最高位
    int getMaxBits(vector<int>& nums) {
        int size = nums.size();
        int max_data = nums[0];
        for (int i = 1; i < size; i++) {
            if (nums[i] > max_data)
                max_data = nums[i];
        }
        int d = 1;
        int radix = 10;
        while (max_data >= radix) {
            d++;
            radix *= 10;
        }
        return d;
    }
};

版权声明:本文为博主原创文章,未经博主允许不得转载。

leetcode | Maximum Gap

标签:linear-sor   sorted   

原文地址:http://blog.csdn.net/quzhongxin/article/details/46968513

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!