leetcode题解-11. Container With Most Water
来源:互联网 发布:按摩棒 知乎 编辑:程序博客网 时间:2024/06/10 15:25
题目:
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.
本题是为了寻找最大容积的两条直线。需要衡量的点主要是高度和宽度之间的权衡。首先我们想到的最简单的思路应该是使用暴力搜索法,使用两次遍历的方法分别对每个数搜索其最大容积。代码入下:
public int maxArea(int[] height) { int max = 0; for(int i=0; i<height.length-1; i++){ int tmp = height[i]; for(int j=i+1; j<height.length; j++){ max = Math.max(max, (j-i)*Math.min(tmp, height[j])); } } return max; }
但是这种方法会产生TLE,时间超出限制。所以我们相到下面的方法,分别从左右两边开始搜索,用max记录最大值,然后不断遍历。每次遍历的依据是看左右两边的值那个大,将小的移向下一位置。代码入下:
public int maxArea1(int[] height){ int max = 0, left=0, right=height.length-1; while(left < right){ if(height[left] < height[right]){ max = Math.max(max, (right-left)*height[left]); left ++; }else{ max = Math.max(max, (right-left)*height[right]); right --; } } return max; }
上面这种方法客击败88。5%的用户,但是我们很显然还可以进行改进,就是每次都移动多次,这样可以省去计算最大值的时间,击败99。2%的用户。代码入下:
public int maxArea2(int[] height) { int lo = 0; int hi = height.length - 1; int max = 0; while(lo < hi) { int min = Math.min(height[lo], height[hi]); max = Math.max(max, min * (hi - lo)); while(lo <= hi && height[lo] <= min) lo++; while(lo <= hi && height[hi] <= min) hi--; } return max; }
0 0
- Leetcode题解:11. Container With Most Water
- leetcode题解-11. Container With Most Water
- 11. Container With Most Water LeetCode题解
- Leetcode题解-11. Container With Most Water
- 【LeetCode】【Python题解】Container with most water
- leetcode题解||Container With Most Water问题
- LeetCode题解:Container With Most Water
- LeetCode题解-11-Container With Most Water
- leetcode题解Java | 11. Container With Most Water
- [模拟]LeetCode 11. Container With Most Water 题解
- LeetCodet题解--11. Container With Most Water
- 11. Container With Most Water题解
- LeetCode 11. Container With Most Water
- [LeetCode]11.Container With Most Water
- LeetCode --- 11. Container With Most Water
- LeetCode 11.Container With Most Water
- [Leetcode] 11. Container With Most Water
- [leetcode] 11.Container With Most Water
- malloc函数是C/C++中常用内存分配库函数,本篇文章将以Linux平台上的malloc为剖析对象,深入了解分配一块内存的旅程。
- C语言常量表达
- iOS开发之检测网络链接的实际状态RealReachability
- java多线程(2):线程通信之生产者消费者模式及等待唤醒机制
- /*****/二叉树经典面试题
- leetcode题解-11. Container With Most Water
- extern "C" __declspec(dllexport) 用法
- 3D 声音实验室开始提供3D音频制作
- sql server 2008 com.microsoft.sqlserver.jdbc.SQLServerException: 通过端口 1433 连接到主机
- 微信公众号开发(四)—— 自定义菜单的创建
- 总结Intent的用法例子
- 【机房重构】下机——职责链模式+策略模式(实践篇)
- Docker之常用命令
- Android 开发 Tip 13 -- generateViewId