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

i指向0位置,j指向最后一个位置,每次移动指向较小数的指针。

 1 public class Solution {
 2     // 暴力解法
 3     public int maxArea(int[] height) {
 4         int max = 0;
 5         for (int i = 0; i < height.length; ++i) {
 6             for (int j = height.length-1; j > i; --j) {
 7                 max = Math.max((j-i)*Math.min(height[i], height[j]),max);
 8             }
 9         }
10         return max;
11     }
12
13     // 双指针
14     public int maxArea(int[] height) {
15         int max = 0;
16         int i = 0, j = height.length-1;
17         while (i < j) {
18             max = Math.max(max, (j-i)* Math.min(height[i], height[j]));
19             if (height[i] < height[j])
20                 i++;
21             else
22                 j--;
23         }
24         return max;
25     }
26
27     public static void main(String[] args) {
28         int[] arg={4,55,55,4};
29         int i = new Solution().maxArea(arg);
30         System.out.println("i = " + i);
31     }
32 }
02-12 04:51