LeetCode. 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.

題目大概是說在笛卡爾座標系中給定n個點, 這n個點的座標都在x軸上方, 向x軸作垂線段可得到x條線段. 從中選擇兩條線段, 使得這兩條線段和x軸形成的水缸得面積最大.

解題思路

最簡單粗暴的方法是窮舉這n22 種組合方式, 不用想也知道妥妥的TLE.

假設有2個指針i, j. i從最左側出發, j從最右側出發. 因爲水缸的高度是由二者中的較小值決定的. 當height[i] < height[j]時, ++ i. 假設i的值不變, – j, 不可能得到更優解(因爲水缸的長度在減小, 高度不可能超過height[i]). 反之, – j. 並記錄每次移動i, j後的水缸面積, 並更新水缸面積的最大值.

源代碼

public class Solution {
    public int maxArea(int[] height) {
        int i = 0, j = height.length - 1;
        int maxArea = getArea(height, i, j);

        while ( i < j ) {
            if ( height[i] < height[j] ) {
                ++ i;
            } else {
                -- j;
            }

            int currentArea = getArea(height, i, j);
            if ( currentArea > maxArea ) {
                maxArea = currentArea;
            }
        }
        return maxArea;
    }

    private int getArea(int[] height, int i, int j) {
        int a = Math.min(height[i], height[j]);
        int b = j - i;

        return a * b;
    }

    public static void main(String[] args) {
        Solution s = new Solution();

        int[] height = {2, 3, 10, 5, 7, 8, 9};
        System.out.println(s.maxArea(height));
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章