[Leetcode 164, Hard] Maximal Gap

来源:互联网 发布:硕士论文数据库 编辑:程序博客网 时间:2024/06/06 08:38

Problem:

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.

Analysis:


Solutions:

C++:

    void RadixSortBinary(vector<int>& nums, int pos)    {        int size = nums.size();        vector<int> zero_bit_index;        vector<int> one_bit_index;        for(int i = 0; i < size; ++i) {            bool get_bit_1(nums[i] >> pos & 1);            if(get_bit_1)                one_bit_index.push_back(i);            else                zero_bit_index.push_back(i);        }                vector<int> temp_nums;        for(int i = 0; i < zero_bit_index.size(); ++i)            temp_nums.push_back(nums[zero_bit_index[i]]);        for(int i = 0; i < one_bit_index.size(); ++i)            temp_nums.push_back(nums[one_bit_index[i]]);                    nums = temp_nums;    }        int maximumGap(vector<int>& nums) {        if(nums.size() < 2)            return 0;                    for(int i = 0; i < 32; ++i)            RadixSortBinary(nums, i);                int diff = 0;        for(int i = nums.size() - 1; i > 0; --i) {            int temp_diff = nums[i] - nums[i - 1];            if(temp_diff > diff)                diff = temp_diff;        }                return diff;    }
Java:


Python:

0 0
原创粉丝点击