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

来源:互联网 发布:每周开户数据 编辑:程序博客网 时间:2024/05/21 02:53

【题目】Given n non-negative integers a1a2, ..., an, where each represents a point at coordinate (iai). n vertical lines are drawn such that the two endpoints of line i is at (iai) 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;}


1 0
原创粉丝点击