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

【leetcode】Maximum Gap

时间:2015-01-24 15:44:53      阅读:201      评论:0      收藏:0      [点我收藏+]

标签:

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.

Credits:
Special thanks to @porker2008 for adding this problem and creating all test cases.

 
 
如果不考虑题目中要求的Linear time/space,实际上只需要先sort,然后找到最大的就可以了。
 1 class Solution {
 2 public:
 3     int maximumGap(vector<int> &num) {
 4        
 5         if(num.size()<2)        
 6             return 0;        
 7        
 8         sort(num.begin(),num.end());       
 9         int max=0;
10        
11         for(int i=0;i<num.size()-1;i++)
12         {
13             if(num[i+1]-num[i]>max)            
14                 max=num[i+1]-num[i];            
15         }
16         return max;
17     }
18 };

 

 
符合题意的方法:
 
由于num中的数字肯定在[min,max]区间内,所以根据抽屉原理,假设num中有n个数字,则最大的gap必然要大于dis=(max-min)/(n-1),所以我们可以把num所在的范围分成等间隔的区间,相邻区间内的元素之间的最大差值,即为要寻找的gap
 
 1 class Solution {
 2 public:
 3     int maximumGap(vector<int> &num) {
 4        
 5         if(num.size()<2) return 0;
 6         if(num.size()==2) return abs(num[0]-num[1]);
 7        
 8         int n=num.size();
 9         int min,max,i;
10        
11         min=max=num[0];
12        
13         for(i=0;i<num.size();i++)
14         {
15             if(min>num[i]) min=num[i];
16             if(max<num[i]) max=num[i];
17         }
18  
19         // 找到区间间隔
20         //注意此处,也可以写成(max-min)/n+1,此时就不需要num.size()==2的边界条件了        
21         int dis=(max-min)/(n-1)+1;
22        
23         vector<vector<int> > bucket((max-min)/dis+1);
24        
25         for(i=0;i<n;i++)
26         {
27             int x=num[i];
28             int index=(x-min)/dis;
29             //把元素放入不同的区间中
30             if(bucket[index].empty())
31             {
32                 bucket[index].reserve(2);
33                 bucket[index].push_back(x);
34                 bucket[index].push_back(x);
35             }
36             else
37             {
38                 if(bucket[index][0]>x) bucket[index][0]=x;
39                 if(bucket[index][1]<x) bucket[index][1]=x;
40             }
41         }
42        
43         int pre=0;
44         int gap=0;
45        
46         //在相邻的区间中(区间内有元素的相邻区间)寻找最大的gap
47         for(i=1;i<bucket.size();i++)
48         {
49             if(bucket[i].empty()) continue;
50            
51             int tmp=bucket[i][0]-bucket[pre][1];
52             if(gap<tmp) gap=tmp;
53             pre=i;
54         }
55         return gap;
56     }
57 };

  

【leetcode】Maximum Gap

标签:

原文地址:http://www.cnblogs.com/reachteam/p/4245961.html

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