[LeetCode] Container With Most Water 简要分析

前言

这题非要说贪心的话也算是吧,不过最主要的特征还是双指针。LC的题好像不少都是扔倆头尾指针然后遍历一遍完事儿的。这道题倒是“短板效应”的不错体现了。

题目

题目链接

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 container contains the most water.
Note: You may not slant the container.

思路

自己做的PPT

图片看不清楚的话可右键复制链接转到图床再看。

代码

 1 class Solution {
 2 public:
 3     int maxArea(vector<int>& height) {
 4         int first = 0;
 5         int end = height.size() - 1;
 6         int result = INT_MIN;
 7         while (first < end) 
 8         {
 9             int width = end - first;
10             int board = height[end]<height[first]?height[end]:height[first];
11             int area = board*width;
12             result = result>area?result:area;
13             if (height[first] <= height[end]) 
14                 first++;
15             else
16                 end--;
17         }
18         return result;
19         }
20 };

 

 

其他

JAVA果然过得比CPP快,Python和C#依旧垫底。

posted @ 2015-12-04 16:42  AllZY  阅读(535)  评论(0)    收藏  举报