【LeetCode】Container With Most Water

Given n non-negative integers a1a2, ..., an, where each represents a point at coordinate (iai). n vertical lines are drawn such that the two endpoints of line i is at (iai) 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.

这题有点像直方图中最大矩形面积,刚开始就看错了,结果不一样,O(n)的算法是看了网上一个大牛的:

class Solution {
public:
    int maxArea(vector<int> &height) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        int size = height.size();
        int ld = 0, rd = size - 1;
        int res = 0;
        if(size <= 1)
            return 0;
        while(ld < rd)
        {
            int h = height[ld] < height[rd] ? height[ld] : height[rd];
            res = max(res,h*(rd-ld));
            if(height[ld] < height[rd])
                ld++;
            else rd--;
        }
        return res;
    }
};
来一个java的,最近在研究java:

public class Solution {
    public int maxArea(int[] height) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        int size = height.length;
        int ld = 0, rd = size - 1;
        int res = 0;
        while(ld < rd)
        {
            int h = height[ld] < height[rd] ? height[ld] : height[rd];
            res = Math.max(res,h*(rd-ld));
            if(height[ld] < height[rd])
                ld++;
            else rd--;
        }
        return res;
        
    }
}



你可能感兴趣的:(LeetCode)