ARTICLE DETAIL

资讯详情

深耕网站建设、视觉设计与SEO优化的一线实战洞察。

【c++】LeetCode:11. Container With Most Water

【c++】LeetCode:11. Container With Most Water

题目表述:Given n non-negative integers a1, a2, …, an, where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the continer contains the most water.

Note: You may not slant the container and n is at least 2.

题目难度:中等

这其实是一个短板原理,一个桶装水的容积与短的木板有关,也是一个优化问题.如果有一系列长短不一的模板,什么时候能够得到的面积最大?

LZ写的代码比较简单,肯定有更好的…

class Solution { public: int maxArea(vector<int>& height) { int l=0, r=height.size()-1; int max_area = 0; while(l<r) { max_area = max(max_area, (r-l)*min(height[l], height[r])); height[l]>height[r]?r--:l++; } return max_area; } };

这题应该是昨天晚上做出来的,但是LZ宿舍的网啊,西湖的水,我的泪~~~~

返回列表