[leetcode]Container With Most Water

来源:互联网 发布:稳定性最好的单片机 编辑:程序博客网 时间:2024/06/03 21:39

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 container contains the most water. 
Note: You may not slant the container and n is at least 2.

前天面试遇到的一道题,当着面试官的面没有做出来,我当时想着类似于84. Largest Rectangle in Histogram的解法,没想到是自己想太多。
这题是标准的双指针类问题,使用两个指针分别指向数组的头和尾向中间遍历(narrow down),每次只移动数值较小的指针,而且如果数值较小的指针向中间缩数值是递减的,则直接跳过。

int maxArea(vector<int>& height){    int N = height.size();    int i = 0, j = N - 1;    int res = 0;    while (i < j)    {        int lower = height[i] < height[j] ? i : j;        res = max(res, height[lower] * (j - i));        // make the lower bar as large as possible in next step        // skip those decreasing numbers        if (lower == i)            for (i = i + 1; i < j && height[i] <= height[i - 1]; ++i);        else            for (j = j - 1; i < j && height[j] <= height[j + 1]; --j);    }    return res;}

祝自己早日找到工作,干巴爹!