偶比豆 2022-08-29 01:02 采纳率: 60%
浏览 40
已结题

力扣11的一个问题//C

这个我是用双指针指向数组数组元素,把指针距离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(indexleft<indexright)
  {
    if(height[indexright]<height[indexleft])
        high=height[indexright];
    else
        high=height[indexleft];
    
    tmp=high*(indexright-indexleft);
    
    if(tmp>Are)
        Are=tmp;
    
    if(height[indexright]<height[indexleft])
        indexright--;
    else
        indexleft++;
  }

  return Are;
}

ps:这个代码是能通过力扣测试的,还有就是学c没多久,可能基础不太好,所以在这提问.

  • 写回答

2条回答 默认 最新

  • 私房菜 优质创作者: 移动开发技术领域 2022-08-29 09:47
    关注

    改成这样的:

      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;
     
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 9月6日
  • 已采纳回答 8月29日
  • 创建了问题 8月29日