leetcode:Container With Most Water(容器装更多的水)
Question:
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.
上边比较简单的表述转化为数学为:给定一个数组height[n];i,j都是数组的下标,找到(j-i)*min( heigth[i],height[j] )最大的数。
算法思想:① 这个题没有想象中的复杂,其实就是TwoSum的思想,设计两个指针i和j, i从左向右扫描,j 从右向左扫描,设计一变量max记录最大值。
② 思想就是 height[i]和heigth[j] 谁小谁移动,假如height[i]<height[j], 在两个选较小的,所以拿(j-i)*height[i]和max比较,如果大于max,max被重新赋值,因为height[i]小,所以i++,向前推进。
③ 对于右边的扫描是同样的道理,最后返回max。
代码设计:
1 class Solution { 2 public int maxArea(int[] height) { 3 int i=0;//从左往右扫描 4 int j=height.length-1;//从右向左扫描 5 int max=0;//用来记录最大值 6 while(i<j){ 7 if(height[i]<height[j]){//如果左边的数小于右边的数 8 if((j-i)*height[i]>max) 9 max=(j-i)*height[i]; 10 i++; 11 } 12 else{//如果右边的数小于左边的数 13 if((j-i)*height[j]>max) 14 max=(j-i)*height[j]; 15 j--; 16 } 17 } 18 return max; 19 } 20 }
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· 全网最简单!3分钟用满血DeepSeek R1开发一款AI智能客服,零代码轻松接入微信、公众号、小程
· .NET 10 首个预览版发布,跨平台开发与性能全面提升
· 《HelloGitHub》第 107 期
· 全程使用 AI 从 0 到 1 写了个小工具
· 从文本到图像:SSE 如何助力 AI 内容实时呈现?(Typescript篇)