标签:11 end start int max height Water Most container
记录加入Datawhale第三天,养成每天做题的好习惯
题目描述:
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.
题目要求找到二个柱子之间空间最大,简单点暴力搜索,每二个柱子之间的空间计算一下,时间复杂度较高O(n^2)。这里使用时间复杂度为O(n)的双指针法,从而头向中间遍历。
Java解法:
1 class Solution { 2 public int maxArea(int[] height) { 3 int start = 0; 4 int end = height.length-1; 5 int max = 0; 6 while(start < end){ 7 max = Math.max(max,Math.min(height[start],height[end])*(end - start)); 8 if(height[start] < height[end]){//二者之间的空间打下取决于最矮的那边,所以每次移动矮的那边 9 start++; 10 }else { 11 end--; 12 } 13 } 14 return max; 15 } 16 }
标签:11,end,start,int,max,height,Water,Most,container 来源: https://www.cnblogs.com/whl-shtudy/p/10453719.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。