首页 > 其他 > 详细

Maximum Gap

时间:2015-12-15 22:52:08      阅读:289      评论:0      收藏:0      [点我收藏+]
Total Accepted: 26010 Total Submissions: 102064 Difficulty: Hard

 

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.

/*

1,2,3,4,5,7
7-1/5=1.2;

0,1.2) 1,2.2)   2.2,3.4)  3.4,4.6)   4.6,5.8)  5.8,7
 0        2        3          4          5        7         
2-1/1.2
3-1/2
*/
class Solution {
public:
    int maximumGap(vector<int>& nums) {
        int nums_size = nums.size();

        int nums_min = nums_size==0 ? 0 : *min_element(nums.begin(),nums.end());
        int nums_max = nums_size==0 ? 0 : *max_element(nums.begin(),nums.end());

        if(nums_size <= 2){
            return nums_max-nums_min;
        }
        if(nums_max-nums_min<=1){
            return nums_max-nums_min;
        }

        vector<int> bucket_max(nums_size,INT_MIN);
        vector<int> bucket_min(nums_size,INT_MAX);
    
        double bucket_gap = (nums_max-nums_min)*1.0/(nums_size-1);
        for(int i=0;i<nums_size;i++){
            int pos = floor((nums[i] - nums_min)/bucket_gap);
            bucket_max[pos] = max(bucket_max[pos],nums[i]);
            bucket_min[pos] = min(bucket_min[pos],nums[i]);
        }
        
        int max_gap = 0 ,pre_bucket_max =bucket_max[0] ;
        for(int i= 1;i<nums_size;i++){
            if(bucket_min[i]==INT_MAX) continue;
            max_gap =  max ( bucket_min[i]-pre_bucket_max,max_gap);
            pre_bucket_max = bucket_max[i];
        }
        return max_gap;
    }
};
//[1,3,4,65,34,2]

 

Maximum Gap

原文:http://www.cnblogs.com/zengzy/p/5049509.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!