蜗牛慢慢爬 LeetCode 11. Container With Most Water [Difficulty: Medium]
2017-09-06 22:10
399 查看
题目
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个非负整数a1,a2,...,an,其中每个表示坐标(i,ai)处的点。绘制n条垂直线,使得线i的两个端点处于(i,ai)和(i,0)。找到两条线,它们与x轴一起形成容器,使得容器含有最多的水。Hints
Related Topics: Array, Two Points容器是有木桶效应的 也就是说短的垂直线决定了整个容器的高 所要求的是 max(短边*坐标差)
找到一些最大值的一般想法是通过可能发生最大值的所有情况,并继续更新最大值。为了提高扫描效率,要找到一种智能的扫描方式来切断无用的情况,同时100%保证通过其他情况可以达到最大值
这儿可以通过设置左右两端的初始指针,向中间扫描,每次只移动较小值的指针 每一次移动都更新最大值
代码
Java
class Solution { public int maxArea(int[] height) { int left,right; left = 0;right = height.length-1; int maxArea = 0; while(left<right){ maxArea = Math.max(maxArea, (right-left)*(Math.min(height[left],height[right]))); if(height[left]<height[right]) left++; else right--; } return maxArea; } }
Python
class Solution(object): def maxArea(self, height): l = 0; r = len(height)-1; maxArea = 0 while l<r: maxArea = max(maxArea, (r-l)*min(height[l],height[r])) if height[l]<height[r]: l += 1 else: r -= 1 return maxArea
相关文章推荐
- 蜗牛慢慢爬 LeetCode 19. Remove Nth Node From End of List [Difficulty: Medium]
- 蜗牛慢慢爬 LeetCode 16. 3Sum Closest [Difficulty: Medium]
- 蜗牛慢慢爬 LeetCode 3. Longest Substring Without Repeating Characters [Difficulty: Medium]
- 蜗牛慢慢爬 LeetCode 22. Generate Parentheses [Difficulty: Medium]
- 蜗牛慢慢爬 LeetCode 15. 3Sum [Difficulty: Medium]
- 蜗牛慢慢爬 LeetCode 6. ZigZag Conversion [Difficulty: Medium]
- 蜗牛慢慢爬 LeetCode 5.Longest Palindromic Substring [Difficulty: Medium]
- 蜗牛慢慢爬 LeetCode 36.Valid Sudoku [Difficulty: Medium]
- 蜗牛慢慢爬 LeetCode 2. Add Two Numbers [Difficulty: Medium]
- 蜗牛慢慢爬 LeetCode 8. String to Integer (atoi) [Difficulty: Medium]
- 蜗牛慢慢爬 LeetCode 10. Regular Expression Matching [Difficulty: Hard]
- 蜗牛慢慢爬 LeetCode 20. Valid Parentheses [Difficulty: Easy]
- 蜗牛慢慢爬 LeetCode 1.Two Sum [Difficulty: Easy]
- 蜗牛慢慢爬 LeetCode 25. Reverse Nodes in k-Group [Difficulty: Hard]
- 蜗牛慢慢爬 LeetCode 7. Reverse Integer [Difficulty: Easy]
- 蜗牛慢慢爬 LeetCode 9. Palindrome Number [Difficulty: Easy]
- # 蜗牛慢慢爬 LeetCode 21. Merge Two Sorted Lists [Difficulty: Easy]
- 蜗牛慢慢爬 LeetCode 23. Merge k Sorted Lists [Difficulty: Hard]
- LeetCode第三关:Longest Substring Without Repeating Characters --> Difficulty: Medium
- LeetCode第二关:Add Two Numbers --> Difficulty: Medium