Skip to content

Commit 6fded09

Browse files
committed
solve #164
1 parent d232122 commit 6fded09

File tree

2 files changed

+62
-0
lines changed

2 files changed

+62
-0
lines changed

src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -151,3 +151,4 @@ mod n0153_find_minimum_in_rotated_sorted_array;
151151
mod n0154_find_minimum_in_rotated_sorted_array_ii;
152152
mod n0155_min_stack;
153153
mod n0162_find_peak_element;
154+
mod n0164_maximum_gap;

src/n0164_maximum_gap.rs

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
/**
2+
* [164] Maximum Gap
3+
*
4+
* Given an unsorted array, find the maximum difference between the successive elements in its sorted form.
5+
*
6+
* Return 0 if the array contains less than 2 elements.
7+
*
8+
* Example 1:
9+
*
10+
*
11+
* Input: [3,6,9,1]
12+
* Output: 3
13+
* Explanation: The sorted form of the array is [1,3,6,9], either
14+
* (3,6) or (6,9) has the maximum difference 3.
15+
*
16+
* Example 2:
17+
*
18+
*
19+
* Input: [10]
20+
* Output: 0
21+
* Explanation: The array contains less than 2 elements, therefore return 0.
22+
*
23+
* Note:
24+
*
25+
*
26+
* You may assume all elements in the array are non-negative integers and fit in the 32-bit signed integer range.
27+
* Try to solve it in linear time/space.
28+
*
29+
*
30+
*/
31+
pub struct Solution {}
32+
33+
// submission codes start here
34+
/*
35+
想不出来, 一看解析居然是 Radix Sort 或 Bucket Sort, 我就 ??? 了...
36+
37+
最佳算法是 Bucket Sort 吗? (桶大小取 max - min / len 那种), 看时间复杂度好像是这样
38+
*/
39+
impl Solution {
40+
pub fn maximum_gap(nums: Vec<i32>) -> i32 {
41+
let mut nums = nums;
42+
nums.sort_unstable();
43+
let mut gap = 0;
44+
for i in 1..nums.len() {
45+
gap = i32::max(nums[i] - nums[i-1], gap);
46+
}
47+
gap
48+
}
49+
}
50+
51+
// submission codes end
52+
53+
#[cfg(test)]
54+
mod tests {
55+
use super::*;
56+
57+
#[test]
58+
fn test_164() {
59+
assert_eq!(Solution::maximum_gap(vec![3,6,9,1]), 3);
60+
}
61+
}

0 commit comments

Comments
 (0)