题目描述:
https://leetcode.com/problems/container-with-most-water/
解决方法:
https://leetcode.com/problems/container-with-most-water/solution/
mycode(c++):
approach1:brute
class Solution {
public:
int maxArea(vector<int>& height) {
int max_area = 0;
for( int i = 0;i<height.size()-1;i++)
for( int j = i+ 1;j< height.size();j++) {
int area = (j - i) * min(height.at(i), height.at(j));
if (area > max_area)
max_area = area;
}
return max_area;
}
};
approach2:(two pointer)
class Solution {
public:
int maxArea(vector<int>& height) {
int max_area = 0;int l = 0 ,r = height.size()-1;
while(l < r ){
max_area = max(max_area,min(height.at(r),height.at(l))*(r-l));
if(height.at(l)<height.at(r))
l++;
else
r--;
}
return max_area;
}
};
心得:
主要还是要具体问题具体分析,根据实际问题分析。
网友评论