Container With Most Water

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

Note: You may not slant the container and n is at least 2.優化

Thinking

本身思考的是用優化後的暴力解法,其中一個用例用了2ms,TLE了,可能時間限制比較嚴格。而後去Discuss大神區看了標準的解法,用的是雙指針(哎,其實原先本身也有想到雙指針,但差距就在於我不知道怎麼設定雙指針的移動條件,從而遍歷出全部取得MaxArea的狀況)。指針

大概思路:創建雙支針,比較兩指針所在的高度,移動高度較小位置的指針(若是移動高度較大位置的指針,因爲指針向中間移動,因此下一個Area一定小於當前Area)code


Answer

public class ContainerWithMostWater {

    // 正解,雙指針,關鍵在於如何遍歷maxArea的狀況
    public int maxArea(int[] height) {
        int left = 0, right = height.length - 1;
        int maxArea = 0;
        
        while (left < right) {
            maxArea = Math.max(maxArea, Math.min(height[left], height[right]) * (right - left));
            if (height[left] < height[right])
                left++;
            else
                right--;
        }

        return maxArea;
    }


//  優化的暴力解法,TLE
//  public int maxArea(int[] height) {
//
//      int res = 0;
//      int ix = 0;
//      for (int i = 0; i < height.length-1; i++){
//          if (height[i] < height[ix]) continue;
//          for (int j = i+1; j < height.length; j++){
//              int area = (j-i) * Math.min(height[i], height[j]);
//              if (area >= res){
//                  res = area;
//                  ix = i;
//              }
//          }
//      }
//
//      return res;
//  }
}
相關文章
相關標籤/搜索