题目链接

盛最多水的容器

题目描述

image.png

实现代码

思想:首先分析问题,对于一个数组nums[n],如果取其两端i 和 j,那么能够盛的水容量为:

Math.min(nums[i], nums[j]) * (j-i)

因此,可以采取双指针的思想,每次移动两端值最小的位置,直到两个指针相遇,实现代码如下:

  1. class Solution {
  2. public int maxArea(int[] height) {
  3. int len = height.length;
  4. if(len == 2) {
  5. return Math.min(height[0], height[1]);
  6. }
  7. int pl = 0;
  8. int pr = len - 1;
  9. int result = Math.min(height[pl], height[pr]) * (len-1);
  10. while (pl < pr) {
  11. if(height[pl] > height[pr]) {
  12. pr--;
  13. } else {
  14. pl++;
  15. }
  16. int current = Math.min(height[pl], height[pr]) * (pr - pl);
  17. if(result < current) {
  18. result = current;
  19. }
  20. }
  21. return result;
  22. }
  23. }