11. Container With Most Water(求能装最多水的容器)

╰半夏微凉° 2022-06-09 14:23 206阅读 0赞

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 and n is at least 2.

题目大意:给定一个长度为n的数组a[n],在二维空间形成n个点(x=i,y=a[i]),找出两个点,使得这两个点到x轴的垂线与x轴构成一个容器,容器的容积最大。容器不能倾斜,而且n>=2。

解题思路:

对于n个点,要求得最大的容积,可以分两种情况:

  1. 宽度为n,高度为a[0]和a[n-1]中较小的值;

  2. 舍弃掉(i,a[i])这个点,其中i = a[0]和a[n-1]中较小的值的下标,然后在剩下的n-1个点中找得两个点,构成容积最大的容器。

直到宽度为1的时候,直接去高度为a[i]。

递归代码:(leetcode测试用例太大,报了StackOverFlow)

  1. class Solution {
  2. public int findMax(int left, int right, int[] height) {
  3. if (right - left == 1) {
  4. return Math.min(height[left], height[right]);
  5. }
  6. int bigger;
  7. if (height[left] > height[right]) {
  8. bigger = findMax(left, right - 1, height);
  9. } else {
  10. bigger = findMax(left + 1, right, height);
  11. }
  12. return Math.max(Math.min(height[left], height[right]) * (right - left), bigger);
  13. }
  14. public int maxArea(int[] height) {
  15. return findMax(0, height.length - 1, height);
  16. }
  17. }

循环代码:(10ms,beats 52.47%)

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

发表评论

表情:
评论列表 (有 0 条评论,206人围观)

还没有评论,来说两句吧...

相关阅读