Chinaunix首页 | 论坛 | 博客
  • 博客访问: 74024
  • 博文数量: 16
  • 博客积分: 31
  • 博客等级: 民兵
  • 技术积分: 187
  • 用 户 组: 普通用户
  • 注册时间: 2010-11-19 19:58
个人简介

一步一个阶梯,向人类进化。

文章分类

全部博文(16)

文章存档

2018年(1)

2015年(3)

2014年(11)

2013年(1)

我的朋友

分类: Java

2014-12-29 16:19:55

Given n non-negative integers a1a2, ..., an, where each represents a point at coordinate (iai). n vertical lines are drawn such that the two endpoints of line i is at (iai) 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.
题目:给定一个数组,数组中的每一个元素代表一条竖直线的长度,其中每两条线组成一个容器,求所有可能的容器中,所能装的最多的水量。
注意:你不会摇晃容器(外国人就是幽默-_-!)。
基本思想:贪心策略。设置两个指针,一个指向数组头,一个指向数组尾,然后不断地向中间移动两个指针。假定我当前两个指针构成的容器并不是最优的,那么我要么增大两个指针的距离,要么增大容器边界的长度。由于遍历过程是从两头开始的,距离最大,所以容器的宽度不能变大,不予考虑,只需考虑增大边界的长度。向中间移动指针的过程中,每次固定一个,移动长度较短的那个指针(有可能会增大边界的长度),以求局部最优。两个指针相交的时候,便求出了最优解。

点击(此处)折叠或打开

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

阅读(1540) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~