如何用Rust语言高效解决LeetCode第11题?
- 内容介绍
- 文章标签
- 相关推荐
本文共计374个文字,预计阅读时间需要2分钟。
问题:给定n个非负整数a1, a2, ..., an,其中每个数代表一个坐标点(i, ai)。画出n条垂直线,使得第i条线的两个端点分别在(i, ai)和(i, 0)。找出两条线,使得它们...
简化版:问题:给定n个坐标点(i, ai),画出n条垂直线。找出两条垂直线,使得它们...
结果输出:无需数词,不超过100字。
Problem
Givennnon-negative integersa1,a2, …,a~n~, where each represents a point at coordinate (i,ai).nvertical lines are drawn such that the two endpoints of lineiis at (i,ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.
**Note:**You may not slant the container andnis at least 2.
The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can containis 49.
Example
Input: [1,8,6,2,5,4,8,3,7]
Output: 49
Solution
impl Solution {
pub fn max_area(height: Vec<i32>) -> i32 {
let mut result: i32 = 0;
let mut start: usize = 0;
let mut end: usize = height.len()-1;
while start < end {
let start_height = height.get(start).unwrap();
let end_height = height.get(end).unwrap();
let h = start_height.min(end_height);
result = result.max(((end-start) as i32 )*h);
if start_height < end_height {
start += 1;
} else {
end -= 1;
}
}
return result;
}
}
本文共计374个文字,预计阅读时间需要2分钟。
问题:给定n个非负整数a1, a2, ..., an,其中每个数代表一个坐标点(i, ai)。画出n条垂直线,使得第i条线的两个端点分别在(i, ai)和(i, 0)。找出两条线,使得它们...
简化版:问题:给定n个坐标点(i, ai),画出n条垂直线。找出两条垂直线,使得它们...
结果输出:无需数词,不超过100字。
Problem
Givennnon-negative integersa1,a2, …,a~n~, where each represents a point at coordinate (i,ai).nvertical lines are drawn such that the two endpoints of lineiis at (i,ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.
**Note:**You may not slant the container andnis at least 2.
The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can containis 49.
Example
Input: [1,8,6,2,5,4,8,3,7]
Output: 49
Solution
impl Solution {
pub fn max_area(height: Vec<i32>) -> i32 {
let mut result: i32 = 0;
let mut start: usize = 0;
let mut end: usize = height.len()-1;
while start < end {
let start_height = height.get(start).unwrap();
let end_height = height.get(end).unwrap();
let h = start_height.min(end_height);
result = result.max(((end-start) as i32 )*h);
if start_height < end_height {
start += 1;
} else {
end -= 1;
}
}
return result;
}
}

