Skip to content

Commit 673f15f

Browse files
author
Zhang Xiaodong
committed
solve 11
1 parent d599d1b commit 673f15f

File tree

4 files changed

+69
-78
lines changed

4 files changed

+69
-78
lines changed

src/problem/mod.rs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +0,0 @@
1-
mod p0004_median_of_two_sorted_arrays;

src/problem/p0004_median_of_two_sorted_arrays.rs

Lines changed: 0 additions & 77 deletions
This file was deleted.

src/solution/mod.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,3 +6,4 @@ mod s0006_zigzag_conversion;
66
mod s0007_reverse_integer;
77
mod s0008_string_to_integer_atoi;
88
mod s0009_palindrome_number;
9+
mod s0011_container_with_most_water;
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
/**
2+
* [11] 盛最多水的容器
3+
*
4+
* 给定一个长度为 n 的整数数组 height 。有 n 条垂线,第 i 条线的两个端点是 (i, 0) 和 (i, height[i]) 。
5+
* 找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。
6+
* 返回容器可以储存的最大水量。
7+
* 说明:你不能倾斜容器。
8+
*
9+
* 示例 1:
10+
* <img alt="" src="https://aliyun-lc-upload.oss-cn-hangzhou.aliyuncs.com/aliyun-lc-upload/uploads/2018/07/25/question_11.jpg" />
11+
*
12+
* 输入:[1,8,6,2,5,4,8,3,7]
13+
* 输出:49
14+
* 解释:图中垂直线代表输入数组 [1,8,6,2,5,4,8,3,7]。在此情况下,容器能够容纳水(表示为蓝色部分)的最大值为 49。
15+
* 示例 2:
16+
*
17+
* 输入:height = [1,1]
18+
* 输出:1
19+
*
20+
*
21+
* 提示:
22+
*
23+
* n == height.length
24+
* 2 <= n <= 10^5
25+
* 0 <= height[i] <= 10^4
26+
*
27+
*/
28+
pub struct Solution {}
29+
30+
// problem: https://leetcode.cn/problems/container-with-most-water/
31+
// discuss: https://leetcode.cn/problems/container-with-most-water/discuss/?currentPage=1&orderBy=most_votes&query=
32+
33+
// submission codes start here
34+
35+
impl Solution {
36+
pub fn max_area(height: Vec<i32>) -> i32 {
37+
let (mut i, mut j) = (0, height.len()-1);
38+
let (mut maxl, mut maxr, mut max_area) = (0usize, 0usize, 0usize);
39+
while i < j {
40+
let area = (j - i) * std::cmp::min(height[j], height[i]) as usize;
41+
if area > max_area {
42+
max_area = area;
43+
maxl = i;
44+
maxr = j;
45+
}
46+
// 不断把短板替换掉
47+
if height[i] < height[j] {
48+
i += 1;
49+
} else {
50+
j -= 1;
51+
}
52+
}
53+
max_area as i32
54+
}
55+
}
56+
57+
// submission codes end
58+
59+
#[cfg(test)]
60+
mod tests {
61+
use super::*;
62+
63+
#[test]
64+
fn test_11() {
65+
assert_eq!(Solution::max_area(vec![1,8,6,2,5,4,8,3,7]), 49);
66+
assert_eq!(Solution::max_area(vec![1, 1]), 1);
67+
}
68+
}

0 commit comments

Comments
 (0)