1. 程式人生 > >【LeetCode】Container With Most Water

【LeetCode】Container With Most Water

Description

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.

Code

class Solution {
public:
    int maxArea(vector<int>& height) {
        int left = 0, right = height.size() - 1;
        int maxV = 0, vol;
        while (left != right) {
            vol = (right - left) * min(height[right], height[left]);
            maxV = max(maxV, vol);
            if
(height[left] < height[right]) // 左邊那條線是短板,如果固定左邊的板,讓right--,那麼新形成的容器一定會容積更小! ++left; else --right; } return maxV; } };

Review

這道題中也用了將兩個變數分別初始化為區間頭尾,根據一定條件將頭向後移動,或將尾向前移動的方法。
題中要求的是最大容量,3Sum Closest要求的是最接近的值,或這種情況下可以用這個思路?

這道題中的限制條件是短板長度,既然有一邊是短板了,不妨設左邊是短板,那麼右邊再往左邊靠近,得到的結果肯定比原來的結果還要小,乾脆可以不考慮左邊是短板的其他情況了,直接讓左邊的下一塊板子當左板好了。
3Sum Closest中的限制條件是兩個數的和。可以根據和target的大小關係來決定如何移動數字才能更靠近target一些。