Leetcode 盛水最多的容器

Leetcode 盛水最多的容器_第1张图片

算法思路:

Explanation:

  • Two-pointer technique:

    • Start with two pointers, one at the beginning (left) and one at the end (right) of the height array.
    • Calculate the area formed between the two vertical lines. The area is calculated as: Area = ( right − left ) × min ⁡ ( height[left] , height[right] ) \text{Area} = (\text{right} - \text{left}) \times \min(\text{height[left]}, \text{height[right]}) Area=(rightleft)×min(height[left],height[right])
    • Move the pointer that points to the shorter line inward (either left or right), as moving the shorter line has the potential to increase the maximum area.
    • Repeat this process until the two pointers meet.
  • Time Complexity:

    • The solution runs in O ( n ) O(n) O(n), where n n n is the number of elements in the height array, because each element is processed at most once.

代码:

class Solution {
public:
    int maxArea(vector<int>& height) {
        int left = 0;
        int right = height.size() - 1;
        int maxWater = 0;
        while(left < right) {
            int currentWater = (right - left) * min(height[left], height[right]);
            if(height[left] >= height[right]) {
                right--;
            }else {
                left++;
            }
            maxWater = max(maxWater, currentWater);
        }
        return maxWater;
    }
};

你可能感兴趣的:(leetcode,算法,职场和发展)