leetcode 42. Trapping Rain Water

灰太狼 2022-07-28 04:13 229阅读 0赞

Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.

For example,
Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6.

rainwatertrap.png

The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcos for contributing this image!

  1. int trap(int* height, int heightSize) {
  2. if(height==NULL)
  3. return 0;
  4. if (heightSize < 3)
  5. return 0;
  6. int k = 1, watersum = 0;
  7. while (k < heightSize-1)
  8. {
  9. if (height[k] < height[k - 1])
  10. {
  11. int kk = k + 1;
  12. int endhigh = height[k], endptr=-1;
  13. while (kk < heightSize&&height[kk] < height[k - 1])
  14. {
  15. if (height[kk] > endhigh)
  16. {
  17. endptr = kk;
  18. endhigh = height[kk];
  19. }
  20. kk++;
  21. }
  22. if (kk == heightSize)
  23. {
  24. if (endptr > 0)
  25. {
  26. for (int i = k; i < endptr; i++)
  27. watersum += height[endptr] - height[i];
  28. k = endptr+1;
  29. }
  30. else
  31. k++;
  32. }
  33. else
  34. {
  35. for (int i = k; i < kk; i++)
  36. watersum += height[k - 1] - height[i];
  37. k = kk+1;
  38. }
  39. }
  40. else
  41. k++;
  42. }
  43. return watersum;
  44. }

accepted

发表评论

表情:
评论列表 (有 0 条评论,229人围观)

还没有评论,来说两句吧...

相关阅读