【leetcode】11. Container With Most Water

11. Container With Most Water

  • Problem
  • Solution (贪心)
    • 1、C 8 ms, faster than 65.90% 8 MB, less than 44.59%
    • 2、python 44 ms, faster than 49.21% 11.9 MB, less than 5.21%

Problem

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.

【leetcode】11. Container With Most Water_第1张图片

The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.

Example:

Input: [1,8,6,2,5,4,8,3,7]
Output: 49

Solution (贪心)

1、C 8 ms, faster than 65.90% 8 MB, less than 44.59%

int maxArea(int* height, int heightSize)
{
    int left = 0, right = heightSize - 1;
    int maxArea = 0, currentArea, shortline;
    while (left < right) {
        shortline = (*(height + left)) < (*(height + right)) ? (*(height + left)) : (*(height + right));
        currentArea = shortline * (right - left);
        maxArea = maxArea > currentArea ? maxArea : currentArea;
        if (*(height + left) <= *(height + right)) {
            while (left < right && *(height + left) <= shortline) {
                left++;
            }
        } else {
            while (left < right && *(height + right) <= shortline) {
                right--;
            }
        }
    }
    return maxArea;
}

2、python 44 ms, faster than 49.21% 11.9 MB, less than 5.21%

class Solution(object):
    def maxArea(self, height):
        """
        :type height: List[int]
        :rtype: int
        """
        left = 0
        right = len(height) - 1
        shortline, maxArea = 0, 0
        while left < right:
            shortline = height[left] if height[left] < height[right] else height[right]
            currentArea = shortline * (right - left)
            maxArea = maxArea if maxArea > currentArea else currentArea
            if height[left] < height[right]:
                while left < right and height[left] <= shortline:
                    left += 1
            else:
                while left < right and height[right] <= shortline:
                    right -= 1
        return maxArea

你可能感兴趣的:(算法,leetcode)