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

LeetCode – Refresh – Maximum Gap

时间:2015-03-21 06:22:24      阅读:139      评论:0      收藏:0      [点我收藏+]

标签:

Sorting solution O(nlogn):

 1 class Solution {
 2 public:
 3     int maximumGap(vector<int> &num) {
 4         int len = num.size(), result = 0;
 5         if (len < 2) return 0;
 6         sort(num.begin(), num.end());
 7         for (int i = 0; i < len-1; i++){
 8             result = max(result, num[i+1] - num[i]);
 9         }    
10         return result;
11     }
12 };

 

O(n), bucket sort. The hint gets from leetcode:

Suppose there are N elements and they range from A to B.

Then the maximum gap will be no smaller than ceiling[(B - A) / (N - 1)]

Let the length of a bucket to be len = ceiling[(B - A) / (N - 1)], then we will have at most num = (B - A) / len + 1 of bucket

for any number K in the array, we can easily find out which bucket it belongs by calculating loc = (K - A) / len and therefore maintain the maximum and minimum elements in each bucket.

Since the maximum difference between elements in the same buckets will be at most len - 1, so the final answer will not be taken from two elements in the same buckets.

For each non-empty buckets p, find the next non-empty buckets q, then q.min - p.max could be the potential answer to the question. Return the maximum of all those values.

Analysis written by @porker2008.

 

 1 class Solution {
 2 public:
 3     int maximumGap(vector<int> &num) {
 4         int len = num.size(), result = 0, gMax = INT_MIN, gMin = INT_MAX, blen = 0, index = 0;
 5         if (len < 2) return 0;
 6         for (int i : num) {
 7             gMin = min(gMin, i);
 8             gMax = max(gMax, i);
 9         }
10         blen = (gMax - gMin)/len + 1;
11         vector<vector<int> > buckets((gMax - gMin)/blen + 1);
12         for (int i : num) {
13             int range = (i - gMin)/blen;
14             if (buckets[range].empty()) {
15                 buckets[range].reserve(2);
16                 buckets[range].push_back(i);
17                 buckets[range].push_back(i);
18             } else {
19                 if (i < buckets[range][0]) buckets[range][0] = i;
20                 if (i > buckets[range][1]) buckets[range][1] = i;
21             }
22         }
23         for (int i = 1; i < buckets.size(); i++) {
24             if (buckets[i].empty()) continue;
25             result = max(buckets[i][0] - buckets[index][1], result);
26             index = i;
27         }
28         return result;
29     }
30 };

 

LeetCode – Refresh – Maximum Gap

标签:

原文地址:http://www.cnblogs.com/shuashuashua/p/4355079.html

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