您的位置:首页 > 编程语言 > C语言/C++

leetcode中的Container With Most Water(C语言)

2016-11-29 20:21 579 查看
【题目】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.

给定n个非负整数a1,a2,...,an,其中每个表示坐标(i,ai)处的点。 绘制n条垂直线,使得线i的两个端点在(i,ai)和(i,0)。 找到两条线,其与x轴一起形成容器,使得容器包含最多的水。

【解释】the most water equal to the biggest area.

【解题方式】(1)利用两个for循环,时间复杂度为O(n*n)

for(i=0;i<heightSize-1;i++){
for(j=1;j<heightSize;j++){
}
}
(2)已知求最大面积,即长宽的改变确定最终面积,先保证max宽,然后确定max面积。从两端向中间靠近,改变小的数值(即左边小,指针右移,右边小,指针左移),直到到达中点

/*
Most Water equal to the biggest area;
code by Roy.
*/
int maxArea(int* height, int heightSize) {
int *max = NULL;
int numb = 0,count = 0;
int i = 0,j = 0;
int n = heightSize;
max = (int*)malloc(sizeof(int)*1);
*max = 0;
for(i = 0,j = n-1;i < j;){
if(*(height+i)>*(height+j)){
numb = *(height+j)*(j-i);
*max = *max>numb?*max:numb;
j--;
}
else{
numb = *(height+i)*(j-i);
*max = *max>numb?*max:numb;
i++;
}
}
return *max;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: