这个我是用双指针指向数组数组元素,把指针距离x较小的元素得到面积are
但问题是我在一个while循环里使用了两次同样判断条件的if判断,但又不能放一起。
有没有什么办法能优化一下这两个if.
int maxArea(int* height, int heightSize){
int indexleft=0;
int indexright=heightSize-1;
int Are=0;
int high;
int tmp;
while(indexleftif(height[indexright]else
high=height[indexleft];
tmp=high*(indexright-indexleft);
if(tmp>Are)
Are=tmp;
if(height[indexright]else
indexleft++;
}
return Are;
}
ps:这个代码是能通过力扣测试的,还有就是学c没多久,可能基础不太好,所以在这提问.
改成这样的:
while(indexleft<indexright)
{
int tempIndex= indexright-indexleft;
if(height[indexright]<height[indexleft])
high=height[indexright--];
else
high=height[indexleft++];
tmp=high * tempIndex;
if(tmp>Are)
Are=tmp;
可以这样优化 if 语句
int maxArea(int* height, int heightSize){
int indexleft=0;
int indexright=heightSize-1;
int Are=0;
int high;
int tmp;
while(indexleft<indexright)
{
//使用后置++或--,可以保证 high 的值符合原代码
if(height[indexright]<height[indexleft])
high=height[indexright--];
else
high=height[indexleft++];
//由于 if 语句后会改变 indexright 或 indexleft
//但对于源代码表达式 (indexright-indexleft)的值都只会少 1,所以这里加 1 即可
tmp=high*(indexright-indexleft + 1);
if(tmp>Are)
Are=tmp;
}
return Are;
}