zoukankan      html  css  js  c++  java
  • 11. 盛最多水的容器

    题目:给定 n 个非负整数 a1,a2,...,an,每个数代表坐标中的一个点 (iai) 。在坐标内画 n 条垂直线,垂直线 i 的两个端点分别为 (iai) 和 (i, 0)。找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。

    说明:你不能倾斜容器,且 n 的值至少为 2

     1     //方法一:暴力法
     2     //思路:外层循环从第一个元素开始,与内存循环一次比较,乘积计算选取大值
     3     //时间复杂度:n^2    空间复杂度:1
     4     public int containerWithMostWater1(int[] arr) {
     5         if(arr.length < 2) {
     6             throw new IllegalArgumentException("参数输入错误");
     7         }
     8         int len = arr.length;
     9         int result = 0;
    10         for(int i=0; i<len-1; i++) {
    11             int width = 1;
    12             for(int j=i+1; j<len; j++) {
    13                 int height = arr[i]; 
    14                 if(arr[i] < arr[j]) {
    15                     height = arr[j];
    16                 }
    17                 int temp = width * height;
    18                 if(temp > result) {
    19                     result = temp;
    20                 }
    21             }
    22         }
    23         return result;
    24     }
    25     //方法二:双指针法
    26     //思路:一个指针指向数组头,另一个指针指向数组尾,比较两指针所指元素的大小,小的则继续挪动,大的则停留,每移动一步计算此时的面积
    27     //大小,保存已知的最大面积。(大的不动,小的移动,不管谁移动宽度总在减小,但高度取决于小的,如果小的移动将高度提高了,则有可能得
    28     //到更大的面积值
    29     //时间复杂度:n    空间复杂度:1
    30     public int containerWithMostWater2(int[] arr) {
    31         if(arr.length < 2) {
    32             throw new IllegalArgumentException("参数输入错误");
    33         }
    34         int result = 0;
    35         int left = 0;
    36         int right = arr.length -1;
    37         int temp = 0;
    38         int width = right;
    39         while(left < right) {
    40             if(arr[left] < arr[right]) {
    41                 temp = arr[left] * width;
    42                 if(temp > result) {
    43                     result = temp;
    44                 }
    45                 left++;
    46             } else {
    47                 temp = arr[right] * width;
    48                 if(temp > result) {
    49                     result = temp;
    50                 }
    51                 right--;
    52             }
    53             width--;
    54         }
    55         return result;
    56     }
    无论有多困难,都坚强的抬头挺胸,人生是一场醒悟,不要昨天,不要明天,只要今天。不一样的你我,不一样的心态,不一样的人生,顺其自然吧
  • 相关阅读:
    [转]如何成为强大的程序员?
    Three.JS 学习准备(0)
    jsp生命周期
    form表单文件上传 servlet文件接收
    android 在自定义的listview(有刷新加载项)列表中,数据过少时不能铺满整个屏幕时,header和footer同时显示问题
    jsp处理
    保持listview当前位置
    HTML5应用:setCustomValidity(message)接口
    Hibernate 查询方法
    这个故事很好,希望激励自己前进······
  • 原文地址:https://www.cnblogs.com/xiyangchen/p/10822374.html
Copyright © 2011-2022 走看看