Problem 11

Container With Most Water

Posted by Ruizhi Ma on July 12, 2019

问题描述

https://leetcode.com/problems/container-with-most-water/

解决思路

遇到这种涉及比较的,可以使用DP(后期再用DP实现),另一种思路就是使用双指针,不断计算amount,然后比较替换,得到结果。

问题解惑

后面因为方法countAmount方法没有被新创建的对象直接调用,所以直接return要加this,表明是当前类调用了countAmount方法。

代码

class Solution {
    public int maxArea(int[] height) {
        //corner case
        if(height == null || height.length < 2) return 0;
        
        return this.countAmount(height);
    }
    
    public int countAmount(int[] height){
        int max = 0;
        int amount = 0;
        for(int i = 0; i < height.length; i++){
            for(int j = i + 1; j < height.length; j++){
                //count the amount of the container
                amount = (j - i) * Math.min(height[i], height[j]);
                
                max = Math.max(max, amount);
            }
        }
        
        return max;
    }
}

效率探究

时间效率:O(n^2)
空间效率:O(n^2)

小感想

开始关注代码风格,开始关注代码的逻辑性和结构性。