1
+ /*
2
+
3
+ Date: Dec 14, 2014
4
+ Problem: Maximum Gap
5
+ Difficulty: Hard
6
+ Source: https://oj.leetcode.com/problems/maximum-gap/
7
+ Notes:
8
+ Given an unsorted array, find the maximum difference between the successive elements in its sorted form.
9
+
10
+ Try to solve it in linear time/space.
11
+
12
+ Return 0 if the array contains less than 2 elements.
13
+
14
+ You may assume all elements in the array are non-negative integers and fit in the 32-bit signed integer range.
15
+
16
+ Solution: 1. Time : O(nlogn). Space : O(1);
17
+ Sort the unsorted array, and find the maximum difference.
18
+ 2. Time : O(n). Space : O(n).
19
+ Drawer Theory. If we put n numbers into (n+1) drawers,
20
+ then there must be at least one empty drawer.
21
+ So we can find the maximum difference between two succesive non-empty drawers.
22
+ */
23
+
24
+ class Solution {
25
+ public:
26
+ int maximumGap_1 (vector<int > &num) {
27
+ sort (num.begin (), num.end ());
28
+ int res = 0 ;
29
+ for (int i = 1 ; i < num.size (); ++i) {
30
+ res = max (res, num[i] - num[i-1 ]);
31
+ }
32
+ return res;
33
+ }
34
+ int maximumGap_2 (vector<int > &num) {
35
+ int n = num.size ();
36
+ if (n < 2 ) return 0 ;
37
+ int minVal = num[0 ], maxVal = num[0 ];
38
+ for (int i = 1 ; i < n; ++i) {
39
+ minVal = min (minVal, num[i]);
40
+ maxVal = max (maxVal, num[i]);
41
+ }
42
+ // delta = (maxVal + 1 - minVal) / (n + 1)
43
+ vector<pair<int ,int > > pool (n+2 ,make_pair (-1 ,-1 ));
44
+ for (int i = 0 ; i < n; ++i) {
45
+ int idx = (long long )(num[i] - minVal)* (n + 1 ) / (maxVal + 1 - minVal);
46
+ if (pool[idx].first == -1 ) {
47
+ pool[idx] = make_pair (num[i],num[i]);
48
+ } else {
49
+ pool[idx].first = min (pool[idx].first , num[i]);
50
+ pool[idx].second = max (pool[idx].second , num[i]);
51
+ }
52
+ }
53
+ int last = pool[0 ].second ;
54
+ int res = 0 ;
55
+ for (int i = 1 ; i < n + 2 ; ++i) {
56
+ if (pool[i].first != -1 ) {
57
+ res = max (res, pool[i].first - last);
58
+ last = pool[i].second ;
59
+ }
60
+ }
61
+ return res;
62
+ }
63
+ };
0 commit comments