File tree Expand file tree Collapse file tree 1 file changed +76
-0
lines changed Expand file tree Collapse file tree 1 file changed +76
-0
lines changed Original file line number Diff line number Diff line change
1
+ # 题目
2
+
3
+ 求最大水容器,给定一个包含正整数的数组,a1,a2,...,an。每个元素都可以呈现成一个点(i,ai)。过每个点,做垂直于x轴的垂线,得到对应交点(0,ai)。(0,ai)和(i,ai)构成一条之前。每条直线两两组合,构成一个储水容器,找到存储量最大的那个容器。
4
+
5
+ ** 举例:**
6
+
7
+ ``` stylus
8
+ Input:[1,3,5]
9
+ (0,1) -> (1,1)
10
+ (0,3) -> (2,3)
11
+ (0,5) -> (3,5)
12
+ Output:3
13
+ ```
14
+
15
+ 输入是[ 1,3,5] ,那么一共有三条垂直与x轴的直线,直线两两组合,面积最大为3。
16
+
17
+ # 思路
18
+
19
+ 最大盛水量取决于两边中较短的那条边,而且如果将较短的边换为更短边的话,盛水量只会变少。所以我们可以用两个头尾指针,计算出当前最大的盛水量后,将较短的边向中间移,因为我们想看看能不能把较短的边换长一点。这样一直计算到左边大于右边为止就行了
20
+
21
+ # 代码
22
+
23
+ ** Python:**
24
+
25
+ ``` python
26
+ class Solution (object ):
27
+ def maxArea (self , height ):
28
+ """
29
+ :type height: List[int]
30
+ :rtype: int
31
+ """
32
+ area_tmp = 0
33
+ area_max = 0
34
+ left = 0
35
+ right = len (height) - 1
36
+ while (left < right):
37
+ min_height = min (height[left], height[right])
38
+ area_tmp = (right - left) * min_height
39
+ if area_tmp > area_max:
40
+ area_max = area_tmp
41
8000
+ if height[left] < height[right]:
42
+ left += 1
43
+ else :
44
+ right -= 1
45
+ return area_max
46
+ ```
47
+
48
+ ** C++:**
49
+
50
+ ``` cpp
51
+ class Solution {
52
+ public:
53
+ int maxArea(vector<int >& height) {
54
+ int left = 0;
55
+ int right = height.size() - 1;
56
+ int area_tmp = 0;
57
+ int area_max = 0;
58
+ while (left < right) {
59
+ area_tmp = (right - left) * (height[ left] < height[ right] ? height[ left] : height[ right] );
60
+ if (area_tmp > area_max) {
61
+ area_max = area_tmp;
62
+ }
63
+ if (height[ left] < height[ right] ) {
64
+ left++;
65
+ }
66
+ else {
67
+ right--;
68
+ }
69
+ }
70
+ return area_max;
71
+ }
72
+ };
73
+ ```
74
+
75
+
76
+
You can’t perform that action at this time.
0 commit comments