Skip to content

Commit 8747c01

Browse files
committed
Add solution 164.
1 parent b8267e5 commit 8747c01

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
class Bucket {
2+
var $leftClose;
3+
var $rightOpen;
4+
var $usedFlag;
5+
6+
function __construct() {
7+
$this->leftClose = 0;
8+
$this->rightOpen = 0;
9+
$this->usedFlag = false;
10+
}
11+
}
12+
13+
class Solution {
14+
15+
/**
16+
* @param Integer[] $nums
17+
* @return Integer
18+
*/
19+
function maximumGap($nums) {
20+
if ($nums==null || count($nums)<2) {
21+
return 0;
22+
}
23+
24+
// find the maximum value and the minimum value in array
25+
$max = $nums[0];
26+
$min = $nums[0];
27+
foreach ($nums as $num) {
28+
$max = $max<$num ? $num : $max;
29+
$min = $min>$num ? $num : $min;
30+
}
31+
32+
// the size of bucket must > 1
33+
$bucketSize = intval(max(1, ($max - $min) / (count($nums) - 1)));
34+
$bucketNum = intval(($max-$min) / $bucketSize + 1);
35+
36+
$buckets = array_fill(0, $bucketNum, null);
37+
for ($i=0; $i
38+
$buckets[$i] = new Bucket();
39+
}
40+
41+
// locating correct bucket
42+
foreach ($nums as $num) {
43+
$bucketIndex = intval(($num - $min) / $bucketSize);
44+
45+
if ($buckets[$bucketIndex]->usedFlag == false) {
46+
$buckets[$bucketIndex]->leftClose = $num;
47+
$buckets[$bucketIndex]->rightOpen = $num;
48+
$buckets[$bucketIndex]->usedFlag = true;
49+
} else {
50+
$buckets[$bucketIndex]->leftClose = min($num, $buckets[$bucketIndex]->leftClose);
51+
$buckets[$bucketIndex]->rightOpen = max($num, $buckets[$bucketIndex]->rightOpen);
52+
}
53+
}
54+
55+
$maxGap = 0;
56+
$preRightOpen = $buckets[0]->rightOpen;
57+
for ($i=1; $i
58+
if ($buckets[$i]->usedFlag == false) {
59+
continue;
60+
}
61+
$maxGap = max($maxGap, $buckets[$i]->leftClose-$preRightOpen);
62+
$preRightOpen = $buckets[$i]->rightOpen;
63+
}
64+
65+
return $maxGap;
66+
}
67+
}

0 commit comments

Comments
 (0)